代码之家  ›  专栏  ›  技术社区  ›  athena

在Java中检查一组字符串中的包含

  •  9
  • athena  · 技术社区  · 15 年前

    我有一组字符串。我想检查这个集合是否包含另一个字符串[]。

    Set<String[]> s  = new HashSet<String[]>();
    s.add(new String[] {"lucy", "simon"});
    System.out.println(s.contains(new String[] {"lucy", "simon"}));
    

    但是,会打印false。我的猜测是,这是因为只比较引用,而不是实际字符串。看来,我唯一的选择就是创建一个类,说短语,然后实现 hashCode() equals() (使用 Arrays.hashCode(...) ).

    有没有别的方法达到我想要的?

    7 回复  |  直到 13 年前
        1
  •  13
  •   Ralph    15 年前

    您的猜测是正确的:数组([])没有实现deep equals方法:如果它们是同一个实例,那么它们就是equals。

    最简单的解决方案是:替换 String[] 通过 List<String>

    另一种方法(但我不建议这样做)是实现自己的集合,它不基于 Object.equals 但关于 java.util.Arrays.equals(Object[]a, Object[]b)

        2
  •  11
  •   Sanjay T. Sharma    15 年前

    转换为 String[] List<String> 结果应该很好。

    Set<List<String>> s  = new HashSet<List<String>>();
    s.add(Arrays.asList("lucy", "simon"));
    System.out.println(s.contains(Arrays.asList("lucy", "simon")));
    
        3
  •  3
  •   haylem    14 年前

    字符串[]中的元素是否可以按不同的顺序排列,并且仍然使整个数组被视为与另一个按其他顺序包含相同元素的数组相等?如果是,那么最好实现一个容器类并重写equals和hashcode。

    如果不是,并且可以将内部元素存储为列表而不是数组,则可以执行以下操作:

    package com.stackoverflow;
    
    
    import java.util.Arrays;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    
    public class StringContainment {
    
      public static void main(final String[] args) {
        final Set<String[]> s = new HashSet<String[]>();
        final Set<List<String>> s2 = new HashSet<List<String>>();
    
        s.add(new String[] {"lucy", "simon"});
        s2.add(Arrays.asList(new String[] { "lucy", "simon" }));
    
        System.out.println(s.contains(new String[] {"lucy", "simon"})); // false
        System.out.println(s2.contains(Arrays.asList(new String[] {"lucy", "simon"}))); // true
      }
    
    }
    

    第一次检查将返回false,第二次检查将返回true。 如果你能使用列表的话,这样做可能会更容易。

    如果你不能,你仍然可以使用这个,只要你不需要做这个比较太频繁(这绝对不是一个好主意性能明智)。

        4
  •  1
  •   Przemek Kryger    15 年前

    听起来你已经回答了你的问题。一种选择是你已经说过的。另一个是使用 设置> ,因为 等于(对象) 说:

    将指定的对象与此集合进行相等性比较。

        5
  •  1
  •   Emil    15 年前

    使用 Set<Set<String>> Set<List<String>> 而不是 Set<String[]>

    代码:

    List<String> s1=Arrays.asList("1","2"),s2=Arrays.asList("1","2");
    System.out.println(s1.equals(s2) + " "+s1.hashCode()+ " "+s2.hashCode());
    

    输出:

    true 2530 2530
    
        6
  •  0
  •   laher    15 年前

    我只是循环调用数组。等于:

    像这样的:

    boolean contains(Set<String[]> s, String[] item) {
      for(String[] toCompare: s) {
        if(Arrays.equals(toCompare, item)) {
            return true;
        }
      }
      return false;
    }
    

    不确定它是否是最快的,但它应该做得很好

        7
  •  0
  •   Johnny    8 年前

    Java8 stream introduction您可以按以下方式执行:

    Boolean res = s.stream()
      .anyMatch(elm -> elm.equals("lucy") || elm.equals("simon"));