4

私は ArrayList(); を持っています。

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

ここでは、同じ行で equalsIgnoreCase メソッドを含む contains() メソッドをチェックしたいと思います。どうすればできますか?

4

3 に答える 3

5

できません。の契約containsは、それに従うことequalsです。Collectionこれはインターフェースの基本的な部分です。リストを反復処理して各値をチェックするカスタム メソッドを作成する必要があります。

于 2013-07-08T12:24:46.890 に答える
3

これはオブジェクト指向の観点から興味深い質問です。

1 つの可能性は、適切な関心の分離に関して、強制したいコントラクトの責任 (大文字と小文字を区別しない等価性) を、リストではなく、収集された要素自体に移すことです。

String次に、独自の hashCode/equals コントラクトを実装する String オブジェクト (継承なし、クラスは final)の新しいクラスを追加します。

// 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"));
于 2013-07-08T12:35:23.917 に答える