2013-07-08 69 views
4

我有一个ArrayList();检查ArrayList <String>包含(“”)方法与equalsIgnoreCase

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

这里我想检查contains()方法与equalsIgnoreCase方法在同一行。 我该怎么做?

+0

'名单名单=新的ArrayList();',不可能应该是'名单名单=新的ArrayList ( );' –

+0

@PrasadKharkar:这是可能的,因为JDK7 ... – Aquillo

+0

@PrasadKharkar我相信'新的ArrayList <>()'现在也是可以接受的。 – hexafraction

回答

11
boolean containsEqualsIgnoreCase(Collection<String> c, String s) { 
    for (String str : c) { 
     if (s.equalsIgnoreCase(str)) { 
      return true; 
     } 
    } 
    return false; 
} 
5

你不能。 contains的合同是按照equals。这是接口的基本组成部分。您必须编写一个自定义方法遍历列表并检查每个值。

2

从面向对象的角度来看,这是一个有趣的问题。

一种可能性是将您希望强制实施的合同责任(平等而无案例)转移到收集到的要素本身,而不是列表中,关于恰当分离的关注。

然后,您会为您的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")); 
相关问题