list = new ArrayList<>(); list.add("aa...">

Check ArrayList <String> contains a method ("") with equalsIgnoreCase

I have an ArrayList ();

List<String> list = new ArrayList<>(); list.add("aaa"); list.add("BBB"); list.add("cCc"); System.out.println(list.contains("aAa")); 

Here I want to test the contains () method with the equalsIgnoreCase method on the same line. How can i do this?

+4
source share
3 answers
 boolean containsEqualsIgnoreCase(Collection<String> c, String s) { for (String str : c) { if (s.equalsIgnoreCase(str)) { return true; } } return false; } 
+11
source

You can not. The contains contract is that it deviates to equals . This is a fundamental part of the Collection interface. You must write your own method that iterates through the list and validates each value.

+5
source

This is an interesting question from the point of view of the TOE.

One possibility is to transfer responsibility for the contract that you want to ensure (equality without cause) to the elements themselves, rather than to the list, with respect to the proper separation of concerns.

Then you added a new class for your String objects (without inheritance, String class final), where you would execute your own hashCode / equals contract.

 // Strictly speaking, this is not a String without case, since only // hashCode/equals methods discard it. For instance, we would have // a toString() method which returns the underlying String with the // proper case. public final class StringWithoutCase { private final String underlying; public StringWithoutCase(String underlying) { if (null == underlying) throw new IllegalArgumentException("Must provide a non null String"); this.underlying = underlying; } // implement here either delegation of responsibility from StringWithoutCase // to String, or something like "getString()" otherwise. public int hashCode() { return underlying.toLowerCase().hashCode(); } public boolean equals(Object other) { if (! (other instanceof StringWithoutCase)) return false; return underlying.equalsIgnoreCase(other.underlying); } } 

The objects that populate the collection will be instances of StringWithoutCase :

 Collection<StringWithoutCase> someCollection = ... someCollection.add(new StringWithoutCase("aaa")); someCollection.add(new StringWithoutCase("BBB")); someCollection.add(new StringWithoutCase("cCc")); 
+2
source

Source: https://habr.com/ru/post/1490272/


All Articles