this is am learning java now. I just want to know whether should we write any comparator for comparing the list of objects with a particular object? And i also want to know why the particular line is not comparing the list
myList.contains(obj1)
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class createItem {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] itemid = null;
try{
File itemFile = new File("C:\\"+"Sano"+".xml");
itemFile.createNewFile();
List<ObjectIdName> myList = new ArrayList<ObjectIdName>();
ObjectIdName obj1 = new ObjectIdName("ABC","ABC");
myList.add(new ObjectIdName("DEF","DEF"));
myList.add(new ObjectIdName("ABC","ABC"));
if(myList.contains(obj1)){
System.out.println("Has");
}
System.out.println("MyList:" + myList.size());
}
catch(Exception e){
e.printStackTrace();
}
}
}
class ObjectIdName implements Serializable{
private static final long serialVersionUID = 1L;
private String id;
private String name ;
public ObjectIdName (String id, String name) {
this.id= id;
this.name =name;
}
}
By default,
equals()compares the references:Since
obj1and the second object you insert into the list are two distinct objects,myList.contains(obj1)returnsfalse.To compare the fields,
ObjectIdNamehas to implements its ownequals()method.Note that if you implement
equals(), it is also a good practice to implementhashCode()(even if it’s not used by your code).