[Solved] Prevent to add data in ArrayList of type Class


There’s a pretty simple way to check if an item already exists in the list:

Override the equals method.

You will have to override the equals method inside your ExampleItem class.

I don’t know the contents, ie. code, of your ExampleItem but this is just my guess so I suggest you to change your code accordingly.

public class ExampleItem {

    private String text1, text2;

    @Override
    public boolean equals(Object o) {
        // Check if the given Object 'o' is an instance,
        // ie. same class, of this ExampleItem class
        if (o instanceof ExampleItem) {
            // Cast the object to ExampleItem
            ExampleItem other = (ExampleItem) o;

            // Check if both have same text
            // (I'm guessing that you only wanted to
            //   compare the text1 variable, otherwise,
            //   check comment below.)
            // Objects.equals() will evaluate whether
            // both text are the same
            return Objects.equals(this.text1, other.text1); // 'this' is unnecessary, only to show

            // If you want to check both then uncomment
            // the code below and remove the one above
            // return Objects.equals(text1, other.text1) && Objects.equals(text2, other.text2);
        }

        // If above fails then I'll just use the
        // before-overwritten equals to avoid
        // writing myself each tiny bit of
        // its implementation
        return super.equals(o);
    }

    public ExampleItem(String text1) {
        this.text1 = text1;
    }

    public ExampleItem(String text1, String text2) {
        this.text1 = text1;
        this.text2 = text2;
    }

    public String getText1() {
        return text1;
    }

    public void setText1(String t1) {
        text1 = t1;
    }

    public String getText2() {
        return text2;
    }

    public void setText2(String t2) {
        text2 = t2;
    }

}

The contains method of the List then will use your overridden/custom equals method to compare the given item to other items in it.

And that’s it, just like a plug-and-play kinda code thing. You can now expect your mExampleList.contains(ex) to work.

And surely I hope that it does work and as always, happy coding!

1

solved Prevent to add data in ArrayList of type Class