检查java集合列表中包含的值

时间:2018-01-03 21:26:18

标签: java list

我有List个长数组,名称为Arraycells

List<long[]> Arraycells = new ArrayList<>() ;
Arraycells.add(new long[]{1L, 0L});
Arraycells.add(new long[]{1L, 1L});
Arraycells.add(new long[]{1L, 2L});

我想查看此列表中是否包含长数组对象:

for (long r = 0L; r < 3; r++) {
    for (long c = 0L; c < 3; c++) {
        if (Arraycells.contains(new long[]{r, c})) { // problem is with this statement
            // do something
        }
    }
}

如何检查Arraycells?

3 个答案:

答案 0 :(得分:1)

contains在这里不起作用。您应该使用Arrays.equals进行数组比较。

试试这个:

for (long r = 0L ;r < 3;r++) {
    final long copyR = r;
    for (long c = 0L; c < 3; c++) {
         final long copyC = c;
         final long[] temp = new long[]{copyR, copyC};
         if (Arraycells.stream()
                       .anyMatch(e -> Arrays.equals(e, temp))){  
                    //do something 
         }
    }
}

我们利用Stream::anyMatch方法搜索数组并找到任何匹配的数组Arrays::equals

答案 1 :(得分:1)

Java是一种面向对象的语言,因此您应该更喜欢使用正确的对问题进行建模,而不是直接使用基本数组。这使得例如通过将逻辑封装在equals()中,对象等式比较更容易。您无法覆盖原始数组的equals()

所以你可以定义

public class ArrayCell {

    private final long[] content;

    public ArrayCell(long[] content) {
        this.content = content;
    }

    @Override
    public boolean equals(Object another) {
        if (another == null || another.getClass() != this.getClass()) {
            return false;
        }
        return Arrays.equals(this.content, another.content);
    }
    @Override
    public int hashCode() {
        return Objects.hash(content);
    }         
}

客户端代码变为:

List<ArrayCell> cells = new ArrayList<>() ;
cells.add(new ArrayCell(new long[]{1L, 0L}));
cells.add(new ArrayCell(new long[]{1L, 1L}));
cells.add(new ArrayCell(new long[]{1L, 2L}));

for (long r = 0L; r < 3; r++){
    for (long c = 0L; c < 3; c++){
        if(cells.contains(new ArrayCell(new long[]{r,c}))){
            // contains calls ArrayCell.equals() internally, so this will work
         }
    }
}

答案 2 :(得分:1)

您可能希望使用List<Long>代替long[]尝试其他变体:

List<List<Long>> cells = new ArrayList<>();
cells.add(Arrays.asList(1L, 0L));
cells.add(Arrays.asList(1L, 1L));
cells.add(Arrays.asList(1L, 2L));

for (long i = 0L; i < 3; i++) {
    for (long j = 0L; j < 3; j++) {
        if (cells.contains(Arrays.asList(i, j))) {
            System.out.println("Contains: " + i + ", " + j);
        }
    }
}

另请注意,示例中的代码检查引用相等性,因为数组从equals继承Object。另一方面,List.equals(...)实现检查列表是否包含相同的元素并且顺序相同。