我已经编写了以下代码,即使我使用了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);
}
答案 0 :(得分:6)
由于数组不会覆盖hashCode
类的equals
和Object
的默认实现,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
。