如何删除以下java代码中的重复项?

时间:2015-10-12 13:21:35

标签: java

我已经编写了以下代码,即使我使用了set,​​我也会获得所有重复项。

private void validatingpswwithpattern(String password) throws IOException

  {
            List<String[]> list=new ArrayList<String[]>();
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});


            Set<String[]> hs = new HashSet<String[]>();
             hs.addAll(list);
             list.clear();
             list.addAll(hs);
             System.out.println(list);
}

3 个答案:

答案 0 :(得分:6)

由于数组不会覆盖hashCode类的equalsObject的默认实现,HashSet对于消除重复项无效。

您可以使用TreeSet并提供Comparator<String[]>,以确定两个String数组何时相等。

TreeSet<String[]> set = new TreeSet<> (new Comparator<String[]>() {
  public int compare(String[] o1, String[] o2)
  {
    // write here logic to determine whether o1<o2 (return -1) or
    //                                       o1>o2 (return 1) or 
    //                                       o1 is equal to o2 (return 0)
  }
});
set.addAll(list);

答案 1 :(得分:0)

您可以通过以下方式进行操作。如果你想删除重复的元素,那么你可以这样做。

List<String[]> list=new ArrayList<String[]>();
list.add(new String[]{"raj","duvva","sathish"});
list.add(new String[]{"raj","duvva","sathish"});
list.add(new String[]{"raj","duvva","sathish"});
list.add(new String[]{"raj","duvva","sathish"});
list.add(new String[]{"raj","duvva","sathish"});
list.add(new String[]{"raj","duvva","sathish"});

TreeSet<String[]> set = new TreeSet<String[]>(new Comparator<String[]>() {    
  @Override
  public int compare(String[] o1, String[] o2) {
    return Arrays.equals(o1, o2)? 0 : 1;
  }
});
set.addAll(list);

list = new ArrayList<String[]>(set);

答案 2 :(得分:0)

如果您想使用HashSet,则需要使用String[]List打包到Arrays.asList