• Post Reply Bookmark Topic Watch Topic
  • New Topic

List String Contains Method  RSS feed

 
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


this code shows that contains method is case sensitive. Is there any alternative method or way to make it not case sensitive and thus return true?
 
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Sam,

this code shows that contains method is case sensitive. Is there any alternative method or way to make it not case sensitive and thus return true?


Well, in fact the contains() method uses the Object.equals() method. The String.equals() is case-sensitive. For String comparison, there is a String.equalsIgnoreCase() method. You could define your own datatype implementing its own equals() (and hashCode()!) method which uses String.equalsIgnoreCase() internally.
However, note that contains() is a very expensive method for lists, since all elements could be iterated. Other collection types might be more appropriate.

Regards,
Thomas
 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you keep using String, most other collections have the same impact because you can't use equals() - and that's what almost all collections are using.

However, TreeSet can help you out:

TreeSet uses either the compareTo method of the objects, or (in this case) a Comparator. If the Comparator says the objects are equal (compare returns 0), the objects are equal. With String.CASE_INSENSITIVE_ORDER you can acchieve a collection which ignores the case of all contents.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!