• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to make List.contains(Object) work when you write your own .equals function  RSS feed

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a list of objcts of a class defined by me. I want to use the List.contains(String name) function to tell me if it contains an object of that name. I have overriden the .equals function as shown in [1]. I then use the code at [2] to to test it, with a bit of debugger output as shown in [3]. It is not working, my overriden method is not getting called by List.contains(String name).

Can anyone tell me how to get this to work?

[1]

[2] graphics.getProcedures() returns private List<ProcedureGraphicSet> procedures;


[3]
object name ESLIM_009 compare to ESLIM_009 = true
graphics.getProcedures().get(0).equals("ESLIM_009")= true
graphics.getProcedures().contains("ESLIM_009")= false
 
Huw Morgan
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got the answer on another forum, someone said:

This is a gross violation of the contract for the equals method, and you are basically getting bitten by that. The equals method must be symmetric, meaning this must hold for all objects A and B:



This does not hold for your equals method because for any string A and custom object B:



And, apparently, the List.contains() method is choosing to compare objects that way.

You must iterate through the list and check the names yourself, or use some sort of functional package which provides a List.contains() type method which takes a Predicate object of some sort.
 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yup,
you just need to write your own loop, that's the best way,


you could change it this way

System.out.println( " graphics.getProcedures().get(0).equals(\"ESLIM_009\")= " + graphics.getProcedures().get(0).equals(new MyClass("ESLIM_009")));

then you're not comparing Strings to MyClass,

but


or some derivative thereof, is preferred (imho)
[ February 11, 2008: Message edited by: Bill Shirley ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!