3

I have written the following code and i am getting all the duplicates even i have used 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);
}
Srinath Murugula
  • 560
  • 1
  • 8
  • 30
  • You are adding to the collection an arrays, which are compared by reference. That means all the objects are different, because all have a different references. – Stanislav Oct 12 '15 at 13:23
  • visit following link. it might help you http://stackoverflow.com/a/21985571/4944490 – Krupesh Kotecha Oct 12 '15 at 13:38

3 Answers3

6

Since arrays don't override the default implementation of hashCode and equals from Object class, HashSet is useless for eliminating duplicates.

You could use a TreeSet and supply a Comparator<String[]> that would determine when two String arrays are equal.

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);
Eran
  • 387,369
  • 54
  • 702
  • 768
0

You can do in the following way. If you want to remove duplicate elements, then you can do something in this way.

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);
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94
0

If you want to use HashSet you need to wrap your String[] into a List using Arrays.asList.

LoganMzz
  • 1,597
  • 3
  • 18
  • 31