I will post my code, but just change the names. I’ll add comments when I can add more info.
List<AbstractA> foo = bar.getFoo; // This returns an ArrayList<E> with two objects. Each object has an ID and Price.
List<Name> names = null;
try{
names = someClass.getNames(); // This returns an ArrayList<E> with 10 Name objects. Each one has an ID, name, description
}catch(Exception e){
Log.warn(e);
}
My main goal is compare the two lists. I have…
Iterator<Name> object = names.iterator();
while(object.hasNext()){
Name j = object.next(); // assign next name
System.out.println("j.getId(): " + j.getId()); // This provides me the Id
System.out.println("foo.contains(j.getId()) " + foo.contains(j.getId())); // Keeps spitting out false but I want it to be true
if(foo.contains(j.getId())){
object.remove(); //remove name out of Names list
}
}
I’m not sure if this makes a lot of sense of what I am trying to do.
There are two beans in this program representing foo and name. So they are different objects and I think that may be the issue.
Any suggestions? Sorry if this is VERY vague…
My main question is, if I want to compare an element in these two Lists, what is the best way to do this?
List.contains(…) uses equals() for its comparisons:
equals() doesn’t require the two objects to be the same class, so you can override it like this:
You probably want to override equals() for both, so that a.equals(b) == b.equals(a).
If you’re finding yourself doing this a lot, it may be that an abstract class that they both implement will help.