这篇文章是my previous post的继续。现在,我有一个要编译的代码。唯一的区别是,现在我使用的是自己的类List<Row>
的列表,而不是List<Integer[]>
。请特别注意Row中的hashCode
,因为它提供了编译错误。
public class Row {
private String key;
private Integer[] values;
public Row(String k,Integer[] v) {
this.key = k;
this.values = v;
}
public String getKey() {
return this.key;
}
public Integer[] getValues() {
return this.values;
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if((obj == null) || (obj.getClass() != this.getClass()))
return false;
// object must be Row at this point
Row row = (Row)obj;
return ((key == row.key) && (values == row.values));
}
@Override
public int hashCode () { // HERE I HAVE A PROBLEM. DON'T KNOW HOW TO IMPLEMENT IT
return this.key;
}
}
public class Test {
public static void main(String[] args) {
List<Row> allRows = new ArrayList<Row>();
allRows.add(new Row("0",new Integer[]{1,2,3}));
allRows.add(new Row("0",new Integer[]{1,2,2}));
allRows.add(new Row("1",new Integer[]{1,2,3}));
allRows.add(new Row("2",new Integer[]{1,1,1}));
allRows.add(new Row("2",new Integer[]{1,1,1}));
List<Row> selectedRows = new ArrayList<Row>();
selectedRows.add(new Row("0",new Integer[]{1,2,3}));
selectedRows.add(new Row("2",new Integer[]{1,1,1}));
System.out.println(allRows);
System.out.println(selectedRows);
List<Row> refreshedRows = refreshRows(allRows,selectedRows);
System.out.println(refreshedRows);
}
private static List<Row> refreshRows(List<Row> allRows,List<Row> selectedRows) {
Set<Row> set1 = new HashSet<Row>();
Iterator<Row> it = allRows.iterator();
while(it.hasNext()) {
Row curr = it.next();
if (!set1.add(curr) && selectedRows.contains(curr)) {
it.remove();
}
}
return allRows;
}
}
结果,即
refreshedArray
应该等于:key = "0", values = {1,2,3}
key = "0", values = {1,2,2};
key = "1", values = {1,2,3};
key = "2", values = {1,1,1};
最佳答案
请尝试以下方法。尽管进行了微小的更改,但是大多数代码是由Netbeans IDE 7.0生成的:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Row other = (Row) obj;
if ((this.key == null) ? (other.key != null) : !this.key.equals(other.key)) {
return false;
}
if (!java.util.Arrays.deepEquals(this.values, other.values)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int hash = 3;
hash = 79 * hash + (this.key != null ? this.key.hashCode() : 0);
hash = 79 * hash + java.util.Arrays.deepHashCode(this.values);
return hash;
}
关于java - 用于从ArrayList#1中删除出现在另一个ArrayList#2中并且在ArrayList#1中不唯一的行的代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8809654/