Java的:重复检测ArrayList中? [英] Java: Detect duplicates in ArrayList?
问题描述
我怎么能去检测(返回真/假)一个ArrayList是否包含Java中的相同元素的多个?
How could I go about detecting (returning true/false) whether an ArrayList contains more than one of the same element in Java?
非常感谢,
特里
Many thanks, Terry
修改
忘了提,我不是在寻找比较块与对方但他们的整数值。每个块有一个int,这是什么使他们不同。
我通过调用一个名为getNum的方法找到特定地块的INT(例如表1 [0] [2] .getNum();
Edit Forgot to mention that I am not looking to compare "Blocks" with each other but their integer values. Each "block" has an int and this is what makes them different. I find the int of a particular Block by calling a method named "getNum" (e.g. table1[0][2].getNum();
推荐答案
最简单的:转储整个集合到一个组(使用(集合)集合构造或Set.addAll),然后看是否设置有大小相同该ArrayList
Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.
List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);
if(set.size() < list.size()){
/* There are duplicates */
}
更新:如果我正确理解你的问题,你有块的二维数组,如
Update: If I'm understanding your question correctly, you have a 2d array of Block, as in
块表[] [];
和要检测,如果其中任何行有重复?
and you want to detect if any row of them has duplicates?
在这种情况下,我可以做到以下几点,假设座实现等于和散列code正确的:
In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:
for (Block[] row : table) {
Set set = new HashSet<Block>();
for (Block cell : row) {
set.add(cell);
}
if (set.size() < 6) { //has duplicate
}
}
我不是100%肯定的,对于语法,所以它可能是更安全的把它写成
I'm not 100% sure of that for syntax, so it might be safer to write it as
for (int i = 0; i < 6; i++) {
Set set = new HashSet<Block>();
for (int j = 0; j < 6; j++)
set.add(table[i][j]);
...
这篇关于Java的:重复检测ArrayList中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!