Home > Software design >  check if an element exists in queue of array in Java
check if an element exists in queue of array in Java

Time:08-30

I have a queue of arrays in Java. What is the easiest way to check if the array already exists in the queue?

Queue<Integer[]> q = new LinkedList<>();
if(!q.contains(new Integer[]{r,c})) {
    q.add(new Integer[]{r, c});
}

I know what I am checking for is an object and even if an array with same values as r and c already exists in the queue, it will be considered as a different object and returns false.

Brute force way is to convert the array to string using Arrays.toString(arr) and loop through the queue and check if the value exists.

I am looking for any other efficient way to do the same.

CodePudding user response:

Instead of a queue of Integer[], you should create a subclass and use that for your queue.

public class MyInts {
  public int[] myInts;
  public int[] getInts() {
    return myInts;
  }
  public boolean equals(MyInts ints) {
    if (!myInts.length == ints.myInts.length) return false;
    int i = 0;
    while (myInts[i] == ints.myInts[i] && i < myInts.length) {
      i  ;
    }
    return i == myInts.length;
  }
}

CodePudding user response:

What you can do is write a wrapper for your object. I am using a record here but a regular class would work as well. The record needs to override equals to use Arrays.equals() for the comparison. I also overrode toString to display the array when the object is printed.

record MyInt(int[] val) {   
    @Override
    public boolean equals(Object ob) {
        if (!(ob instanceof MyInt)) {
            return false;
        }
        MyInt myOb = (MyInt)ob;
        return Arrays.equals(val, myOb.val);
    }
    @Override
    public String toString() {
        return Arrays.toString(val);
    }
}

Define the queue and some data

Queue<MyInt> queue =
        new LinkedBlockingDeque<>();

List<MyInt> data = List.of(
        new MyInt(new int[] {1,2}),
        new MyInt(new int[] {2,3}),
        new MyInt(new int[] {3,4}),
        new MyInt(new int[] {4,5}),
        new MyInt(new int[] {1,2}),
        new MyInt(new int[] {2,3}),
        new MyInt(new int[] {3,4}),
        new MyInt(new int[] {5,6}));

Add the data as in your question.

for (MyInt mi : data) {
    if(!queue.contains(mi)) {
        queue.add(mi);
    }
}
                
queue.forEach(System.out::println);

prints

[1, 2]
[2, 3]
[3, 4]
[4, 5]
[5, 6]      
  • Related