我正在编写一段代码,其中包含具有重复项的元组列表,并且我想从该列表中删除重复项,而不使用 HASHSET 或 SET。我只被允许使用 Arrays、ArrayList 和 Iterator。
下面的代码将会溢出/无限循环。我明白为什么它会无限循环,因为我添加了元素并且大小也增加了。
元组类:
public class Tuple {
private int key;
private String value;
public Tuple(int keyP, String valueP) {
key = keyP;
value = valueP;
}
public int getKey() {
return key;
}
public String getValue() {
return value;
}
public boolean equals(Tuple t) {
if (this.key == t.getKey() && this.value.equals(t.getValue())) {
return true;
}
else return false;
}
}
ArrayList < Tuple > union= new ArrayList<Tuple>();
ArrayList < Tuple > unique= new ArrayList<Tuple>();
Union: [Tuple < 15, a >, Tuple < 17, a >, Tuple < 15, a >, Tuple<79, b>]
unique.add(union.get(0));
for (int k = 1; k < union.size(); k++) {
Tuple test= union.get(k);
for (int j= 0; j < unique.size();j++) {
if (!test.equals(unique.get(j))) {
System.out.println(union.get(k));
unique.add(union.get(k));
}
}
}
应该是独一无二的
[Tuple< 15, a >, Tuple< 17, a >, Tuple< 79, b >]
我已经被困了一天多了。请帮帮我。
最佳答案
重写 Tuple 的键、值变量上的 equals()
和 hashCode()
方法。然后你可以直接使用List的contains()
方法,而不是每次都循环遍历unique
List。
文件:Tuple.java
public class Tuple {
private int key;
private String value;
public Tuple(int keyP, String valueP) {
key = keyP;
value = valueP;
}
public int getKey() {
return key;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return "Tuple [key=" + key + ", value=" + value + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + key;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tuple other = (Tuple) obj;
if (key != other.key)
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
}
文件:TupleMain.java
public class TupleMain {
public static void main(String[] args) {
List<Tuple> union = Arrays.asList(new Tuple(15, "a"), new Tuple(17, "a"), new Tuple(15, "a"),
new Tuple(79, "b"));
List<Tuple> unique = new ArrayList<Tuple>();
unique.add(union.get(0));
for (int k = 1; k < union.size(); k++) {
Tuple test = union.get(k);
if (!unique.contains(test)) {
unique.add(test);
}
}
System.out.println(unique);
// The Java 8 way
union.stream().distinct().forEach(System.out::println);
}
}
关于java - 如何将重复元组列表转换为唯一元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49165234/