Just implement the equals()
method:
class MyList {
private String x;
public MyList (String x) {
this .x = x;
}
@Override
public String toString () {
return x;
}
public static void main ( String [] args ) {
List<MyList> ts = new ArrayList<MyList>();
ts.add (new MyList ("one"));
ts.add (new MyList ("two"));
ts.add (new MyList ("three"));
MyList t = new MyList("one");
System.out.println ("Is t in ts? " + ts.contains(t));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((x == null) ? 0 : x.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MyList other = (MyList) obj;
if (x == null) {
if (other.x != null) {
return false;
}
} else if (!x.equals(other.x)) {
return false;
}
return true;
}
}
Output Is t in ts? true
The equals()
Method is defined for the class Object
which is the top class for every class. The contains()
Method contractually checks, if the requested object a is contained in the list (i.e. same object is contained in a list) or if an equal object b (i.e. a.equals(b) is true) is contained in the list.
For List.contains(obj)
the hashCode
method is not required to be implemented, however, it is recommended to implement hashCode()
whenever you implement equals()
and make sure to depend on the same attributes in both methods.