4

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.

9
  • Is Java 8+ allowed? Commented Nov 23, 2017 at 16:05
  • If your list contained a class that holds two integers, and if that class overrides equals and hashCode, reflecting what those integers are, then simply call contains(...) on the list. If you went this route, then best to make the class immutable. Commented Nov 23, 2017 at 16:05
  • Consider using a Set and creating a class for your integer-pairs with correct equals and hashcode methods. Commented Nov 23, 2017 at 16:06
  • 1
    Possible duplicate of Using contains on an ArrayList with integer arrays Commented Nov 23, 2017 at 16:08
  • 1
    Use a Set<Point>> instead: no duplicates as .equals okay and add then returns false. Commented Nov 23, 2017 at 16:11

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Abbreviations are bad practice and discouraged unless they are universally accepted such as Utils. Coordinate is therefore preferred.
Caveat: If you're going to use the x and y fields within equals and hashCode, then they should be immutable (as per my comment to the OP's question).
@chsdk Rather than a class we can use Stream with Set to make it short.
@HovercraftFullOfEels I just tried to produce a quick class for the example purpose, yes it would be better defined it as immutable. Thank you for the tip anyway :)
@ShubhenduPramanik Yes it would be another good alternative to use Stream and yes for the Set point, I was about pointing it out.
2

Well, you can do it the dumb way:

boolean exists = false;
for (Integer[] integers : list) {  // list being the LinkedList
    if (Arrays.equals(integers, value)) {
        exists = true;
        break;
    }
}
if (!exists) {
    list.add(value);
}

1 Comment

I'd suggest doing what chsdk posted though.
2

You can use Stream with Set to solve your problem like below:

 List<Set<Integer>> list = new LinkedList<>();
    list.add(Stream.of(1, 2).collect(Collectors.toSet()));

    Set<Integer> s1 = new HashSet<>();
    s1.add(1);
    s1.add(2);

    System.out.println(list.contains(s1));

    Set<Integer> s2 = new HashSet<>();
    s2.add(1);
    s2.add(4);
    System.out.println(list.contains(s2));

O/P:

true

false

N.B: You can use ArrayList because yo preserve the sequence as well.

Comments

0

If you really really want to do that with contains() (or have no other choice by whatever reason), you can implement it like that:

    final Integer[] newPair = {2, 3};
    final boolean exists = values.contains(new Object()
    {
        // note that List.contains() javadoc explicitly specifies that 
        // newPair is used as the receiver not the argument for equals()
        @Override
        public final boolean equals(final Object listElement)
        {
            final Integer[] otherPair = (Integer[]) listElement;
            return Arrays.equals(newPair, otherPair);
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.