Java:检测 ArrayList 中的重复项? [英] Java: Detect duplicates in ArrayList?

查看:38
本文介绍了Java:检测 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?

非常感谢,特里

编辑忘了说,我不是要比较块",而是要比较它们的整数值.每个块"都有一个 int,这就是它们不同的原因.我通过调用名为getNum"的方法(例如 table1[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(使用 Set(Collection) 构造函数或 Set.addAll),然后查看 Set 的大小是否与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?

在那种情况下,假设 Block 正确实现了equals"和hashCode",我可以执行以下操作:

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]);
 ...

Set.add 如果要添加的项目已经在集合中,则返回布尔值 false,因此您甚至可以短路并打包任何返回 false 的添加项如果您只想知道是否有任何重复.

Set.add returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns false if all you want to know is whether there are any duplicates.

这篇关于Java:检测 ArrayList 中的重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆