List<MyModel>.contains(MyModel) java is not working

I have my Class MyModel which contains:

private int value;

public int getValue() {
    return value;
}

public void setValue(int value) {
    this.value = value;
}

Now I have populated MyModel class:

private final List<MyModel> listModel = new ArrayList<>();
private Mymodel myModel;

 myModel= new MyModel ();
 myModel.setValue(1);
 myModel.setValue(2);
 myModel.setValue(3);
 listModel.add(myModel);

I want to find out if listModel contains myModel

listModel.contains(myModel)

I have made some search and I know contains makes use of the equals but I am finding the right way to find the solution. Thanks in advance

If you look at the implementation of contains in ArrayList class, you'd see that internally it is using the equals method to find the object:

public boolean contains(Object o) {
    return indexOf(o) >= 0;
}

public int indexOf(Object o) {
    return indexOfRange(o, 0, size);
}

int indexOfRange(Object o, int start, int end) {
    Object[] es = elementData;
    if (o == null) {
       ...
    } else {
        for (int i = start; i < end; i++) {
            if (o.equals(es[i])) { //calling overridden equals of the object instance, else it will revert to the Object's equals which simply compares the reference 
                return i;
            }
        }
    }
    return -1;
}

So you'd be needing to create both equals and hashCode for your MyModel class. You can take the help of the IDE you are using to generate it for you:

As an example:

class MyModel{
    private int value;

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof MyModel)) return false;
        MyModel myModel = (MyModel) o;
        return value == myModel.value;
    }

    @Override
    public int hashCode() {
        return Objects.hash(value);
    }
}

List N: Disinfectants for Use Against SARS-CoV-2 (COVID-19), More on Lists�. The list data type has some more methods. Here are all of the methods of list objects: list. append (x). Add an item to the end of the list. The Best Online To Do List App For Your Team! Start Your Free Trial Today! Manage Your Team's Projects & To-Dos in One Online Space! Try It For Free.

The only way to check for contains is to override equals() method. If you check how contains method is implemented in ArrayList you can easily find it out. contains() method will call indexOf() method which will return the index of a element in the list. If the index is greater than 0, then it contains() method will return true.

Lets look how indexOf() method is implemented.

public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

This means indexOf() method is just traversing through elements in the list and calling equals() method in your MyModel class.

So there is no other way to check for contains without overriding equals() method from Object class

list - Manual, Sequence Types — list , tuple , range �. There are three basic sequence types: lists, tuples, and range objects. Additional sequence types tailored for processing of� Definition of list (Entry 5 of 9) 1 : a band or strip of material: such as. a : listel. b : selvage. c : a narrow strip of wood cut from the edge of a board. 2 lists plural in form but singular or plural in construction. a : an arena for combat (such as jousting) entered the lists against the bull — Frank Yerby.

Try to run the following code, I have modified it and added Logs, now u can check output printed on the console: I would suggest you check for the object by using equals().

class MyModel {
private int value;

public int getValue() {
    return value;
}

public void setValue(int value) {
    this.value = value;
}

@Override
public String toString() {
    return "MyModel{" +
            "value=" + value +
            '}';
}

}

final List<MyModel> listModel = new ArrayList<>();
    MyModel myModel;

    myModel= new MyModel();
    myModel.setValue(1);
    myModel.setValue(2);
    myModel.setValue(3);
    listModel.add(myModel);
    //here your myModel object has '3' value and list has [3], So this will return `true`
    System.out.println("myModel=>"+myModel.toString()+"-->List = "+listModel.toString()+",, CONTAINS. =>"+listModel.contains(myModel));

    myModel= new MyModel();
    myModel.setValue(8);
    listModel.add(myModel);
    //here your myModel object has '8' value and list has [3,8], So this will return `true`
    System.out.println("myModel=>"+myModel.toString()+"-->List = "+listModel.toString()+",, CONTAINS. =>"+listModel.contains(myModel));

    myModel= new MyModel();
    myModel.setValue(100);
    //here your myModel object has '100' value and list has [3,8], So this will return `false`
    System.out.println("myModel=>"+myModel.toString()+"-->List = "+listModel.toString()+",, CONTAINS. =>"+listModel.contains(myModel));

5. Data Structures — Python 3.8.5 documentation, In 1979, the Committee decided to inscribe the Ohrid Lake on the World Heritage List under natural criteria (iii). In 1980, this property was extended to include� list 1. (lĭst) n. 1. A series of names, words, or other items written, printed, or imagined one after the other: a shopping list; a guest list; a list of things to do. 2. A considerable number; a long series: recited a list of dates memorized. v. list·ed, list·ing, lists. v.tr.

Built-in Types — Python 3.8.5 documentation, List definition is - a simple series of words or numerals (such as the names of persons or objects). How to use list in a sentence. List denotes a series of names, items, or figures arranged in a row or rows: a list of groceries. Catalog adds the idea of alphabetical or other orderly arrangement, and, often, descriptive particulars and details: a library catalog.

World Heritage List, Editor's Choice by Google Any.do is a To Do List, Calendar, Planner, Tasks & Reminders App That Helps Over 25M People Stay Organized and Get More Done. list noun (RECORD) A2 [ C ] a record of short pieces of information, such as people's names, usually written or printed with a single thing on each line and often ordered in a way that makes a particular thing easy to find: a shopping list.

List, There are four collection data types in the Python programming language: List is a collection which is ordered and changeable. Allows duplicate members. Tuple � a record of a series of items (as names or titles) usually arranged according to some system. we put eggs, sour cream, tomatoes, roast beef, and cheddar cheese on the shopping list. Synonyms for list. canon, catalog. (or catalogue), checklist, listing, menu,

Comments
  • There's really no other way to do this besides implementing equals. You should implement equals.
  • And a modern IDE will help you with implementing it properly
  • If you have one primitive field that can identify the MyModel uniquely that is an int id for example then you can get the list of the fields from List<MyModel> and search for myModel.id in it.
  • "contains makes use of the equals but I am finding the right way to find the solution" - implementing equals() for MyModel IS the right way to use contains() later.
  • Possible duplicate of How does a ArrayList's contains() method evaluate objects?
  • The object (should) always equals itself! The original implementation Object.equals(..) is this == another. The OP do not change the original myModel object's reference, so contains(myModel) must work without make own equals(...).
  • The object (should) always equals itself! The original implementation Object.equals(..) is this == another. The OP do not change the original myModel object's reference, so contains(myModel) must be true without write own equals(...).