| Author |
List String Contains Method
|
Sam Benry
Ranch Hand
Joined: Mar 21, 2008
Posts: 89
|
|
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?
|
 |
Thomas Thevis
Ranch Hand
Joined: Sep 02, 2008
Posts: 87
|
|
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
|
SCJP 5.0, SCJD in progress
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: List String Contains Method
|
|
|