发布于2022-01-09 21:47 阅读(1143) 评论(0) 点赞(28) 收藏(5)
我确实有int
对,即;(整数,整数)
1) 给定 k 个这样的对,检查它们是否唯一。IE; 使用 k 对形成的集合的大小是 k ?
2) 如果给定的 k 条记录是唯一的,则按排序顺序存储它们(按 x 并按 y 解决冲突)
3) 给定 n 个大小为 k 的集合,创建一组集合。
如果 k = 3 ,则要求 1 和 2 的示例
(100, 100) (110, 300) (120, 200) 是一个有效的集合并按顺序排列。
(100, 100) (300, 200) (200, 300) 是一个有效的集合,但没有排序。
(100, 100) (100, 200) (100, 200) 在有效集合中
要求 3
输入示例:
(100, 100) (200, 300) (300, 200)
(100, 100) (200, 300) (300, 200)
(100, 100) (201, 300) (300, 200)
输出:
(100, 100) (200, 300) (300, 200)
(100, 100) (201, 300) (300, 200)
这是与我面临的实际问题最接近的类比。我需要用 Java 完成这项工作,而且我从未在 Java 中工作过。我是一名中级 C++ 程序员。
我可以通过一些丑陋的编码和排序来解决 1 和 2。
但是我无法获得 3。以下是我到目前为止可以获得的 3。类对实现了可比性
(验证码)
import java.util.HashSet;
public class set {
public static void main (String []args) {
HashSet<Pair> s1 = new HashSet();
s1.add(new Pair(10,10));
s1.add(new Pair(10,10));
HashSet<Pair> s2 = new HashSet();
s2.add(new Pair(10,10));
s2.add(new Pair(10,10));
HashSet<HashSet<Pair>> s12 = new HashSet();
s12.add(s1);s12.add(s2);
for ( HashSet<Pair> hs : s12) {
for (Pair p : hs) {
System.out.println(""+ p.toString());
}
}
}
}
看起来您没有在 Pair 类中覆盖equals
和/或hashCode
方法。
例如,如果您的Pair
班级具有以下结构:
protected K value1;
protected V value2;
你应该实现equals
和hashCode
as(example) :
public boolean equals(Object obj) {
if (!(obj instanceof Pair))
return false;
Pair that = (Pair)obj;
boolean result = true;
if (this.getValue1() != null)
result = this.getValue1().equals(that.getValue1());
else if (that.getValue1() != null)
result = that.getValue1().equals(this.getValue1());
if (this.getValue2() != null)
result = result && this.getValue2().equals(that.getValue2());
else if (that.getValue2() != null)
result = result && that.getValue2().equals(this.getValue2());
return result;
}
public int hashCode() {
int result = value1 != null ? value1.hashCode() : 0;
result = 31 * result + (value2 != null ? value2.hashCode() : 0);
return result;
}
作者:黑洞官方问答小能手
链接:http://www.javaheidong.com/blog/article/375984/fe67823673ab7d6b0c58/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!