Checking the value contained in the java List collection

I have Listlong arrays with the name Arraycells:

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

I want to see if this list contains a long array:

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
        }
    }
}

How can I check Arraycells?

+4
source share
3 answers

You might want to try another option, using List<Long>instead 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);
        }
    }
}

Also note that the code in your example checks for reference equality, because arrays inherit equalsfrom Object. On the other hand, the implementation List.equals(...)checks if the lists contain the same elements and in the same order.

+1
source

containsdoes not work here. you should use an Arrays.equalsarray to compare.

:

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 :: .

+1

Java is an object-oriented language, so you should prefer to model the problem using the appropriate class, rather than using a primitive array directly. This makes, for example, object equality comparisons easier by encapsulating the logic in equals(). You cannot override equals()for primitive arrays.

So you can define

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);
    }         
}

And the client code will look like this:

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
         }
    }
}
+1
source

Source: https://habr.com/ru/post/1691708/


All Articles