有时要把有重复的数据用set去掉重复元素,但用set后又把元素顺序打乱了,今天想了一个解决方法:
//使用set+list排序
hashSet = new HashSet();
System.out.println( "使用set+list排序 Add elements into hashSet ");
arrayList = new ArrayList();
if(hashSet.add(20)){
System.out.print(20 + " ");
arrayList.add(20);
}
if(hashSet.add(19)){
System.out.print(19 + " ");
arrayList.add(19);
}
if(hashSet.add(19)){
System.out.print(19 + " ");
arrayList.add(19);
}
if(hashSet.add(19)){
System.out.print(19 + " ");
arrayList.add(19);
}
if(hashSet.add(18)){
System.out.print(18 + " ");
arrayList.add(18);
}
if(hashSet.add(19)){
System.out.print(19 + " ");
arrayList.add(19);
}
System.out.println( "\nThe elements in 使用set+list排序 arrayList is : ");
System.out.println(arrayList);
System.out.println( "\n ");
//输出结果:使用set+list排序 Add elements into hashSet //20 19 18 //The elements in 使用set+list排序 arrayList is : //[20, 19, 18]