Это интересный вопрос с точки зрения ОО.
Одна из возможностей заключается в передаче ответственности по контракту, который вы хотите обеспечить (равенство без случая), самим собранным элементам, а не списку, в отношении надлежащего разделения озабоченности.
После этого вы добавили бы новый класс для объектов String (без наследования, String
class final), где вы бы выполнили свой собственный контракт hashCode/equals.
// 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);
}
}
Объекты, населяющие коллекции будет экземпляры StringWithoutCase
:
Collection<StringWithoutCase> someCollection = ...
someCollection.add(new StringWithoutCase("aaa"));
someCollection.add(new StringWithoutCase("BBB"));
someCollection.add(new StringWithoutCase("cCc"));
'Список список = новый ArrayList();', не возможно это должно быть 'Список список = новый ArrayList (); ' –
@PrasadKharkar: Возможно, так как JDK7 ... – Aquillo
@PrasadKharkar Я считаю, что' new ArrayList <>() 'также приемлемо в наши дни. – hexafraction