从面向对象的角度来看,这是一个有趣的问题。
一种可能性是将您希望强制实施的合同责任(平等而无案例)转移到收集到的要素本身,而不是列表中,关于恰当分离的关注。
然后,您会为您的String对象添加一个新类(没有继承,String
类是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我相信'新的ArrayList <>()'现在也是可以接受的。 – hexafraction