Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object exists in a LinkedList in java?

A LinkedList contains a set of Integer[]. Each Integer[] in the list has 2 numbers. Ex of the linked list:

Integer[]{1,2}, Integer[]{2,3}.....

Before adding another Integer[] to this LinkedList, I wanto check if another Integer[] with the same data already exists.

Ex: Object to add = Integer[] {2,3}. But this already exists in the LinkedList.

So I want to avoid adding this.

How to verify that object already exists? Is there an inbuild function that can be used? contains() didnt do the trick.

like image 639
user811433 Avatar asked Jan 04 '23 04:01

user811433


1 Answers

I think you better use a specific class if you are treating coordinates, as an Integer[] is useless for only two numbers, and will cause some problems with contains() and other List methods like .sort() as well.

You better create a Coordinate class, which will hold the two values:

public class Coordinate{
    private int x;
    private int y;

    //getters and setters, constructor
    @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof Coord)) {
            return false;
        }
        Coordinate coord = (Coordinate) o;
        return coord.x == x &&
                coord.y == y;
    }

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + x;
        result = 31 * result + y;
        return result;
    }
}

Then you can use:

LinkedList<Coordinate>

Note:

Note that using a Set implementation will be better here, it will prevent having duplicates in the set of coordinates, so we don't need to check for it manually.

like image 124
cнŝdk Avatar answered Jan 05 '23 18:01

cнŝdk