如何从二维 int 数组构造 ArrayList? [英] How to construct ArrayList from 2D int array?
本文介绍了如何从二维 int 数组构造 ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 2D int 数组,例如我想删除重复的行
I have a 2D int array, i want to remove duplicate rows for example
30,40,50
50,30,40
30,40,50
在上面的例子 2nd &第三行与第一行重复.
in above example 2nd & 3rd row is duplicate of 1st row.
我知道 ArrayList
可以动态增长和下沉,这对于这个概念是有用的类,但是我们如何将 int[][]
转换为 ArrayList
.
I know ArrayList
can dynamically grow and sink which is useful class for this concept but how we convert int[][]
into ArrayList
.
推荐答案
首先,你应该创建一个类来保存你的数据,这些数据覆盖了 public boolean equals(Object obj)
和 public inthashCode()
表示数据的相等性.
First, you should create a Class to hold you data which override public boolean equals(Object obj)
and public int hashCode()
to indicate equality of the data.
public class Row {
private int[] ints;
public Row(int[] ints) {
this.ints = ints.clone();
Arrays.sort(this.ints);
}
@Override
public int hashCode() {
return Arrays.hashCode(ints);
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Row) {
Row another = (Row) obj;
int[] original = Arrays.copyOf(another.ints, another.ints.length);
return Arrays.equals(ints, original);
} else {
return false;
}
}
@Override
public String toString() {
return Arrays.toString(ints);
}
}
测试用例
public class Test {
public static void main(String[] args) {
int[][] arrays = new int[][]{{30,40,50}, {50,30,40}, {30,40,50}, {10, 20, 30}};
Set<Row> rows = new HashSet<Row>();
for(int[] a: arrays) {
rows.add(new Row(a));
}
for(Row row: rows) {
System.out.println(row);
}
}
}
输出
[10, 20, 30]
[30, 40, 50]
这篇关于如何从二维 int 数组构造 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文