list set接口之间的区别

时间:2023-03-09 01:07:02
list  set接口之间的区别

list接口它的实现类,比如arraylist里面的值有序,并且可以重复。(有序指的是插入进去的顺序)

set无序,且不可重复。(这里的无序就是指不是插入进去的顺序,但其实也不是真的无序,它会按照自己的逻辑进行排序,比如hashset会按照hash值进行排序,treeset会按照自然顺序进行排序)

list  set都可以插入null

public static void test(){
List a = new ArrayList();
a.add(2);
a.add(1);
a.add(3);
a.add(4);
a.add(4);
a.add(null);
a.add(null);
// for(int i=0; i<a.size(); i++){
// System.out.println(a.get(i));
// }
// for(Object i : a){
// System.out.println(i);
// }
Iterator it = a.iterator();
while(it.hasNext()){
Object i = it.next();
System.out.println(i);
}
}

输出:

2
1
3
4
4
null
null

public static void testSet(){
Set a = new HashSet();
a.add("123");
a.add("124");
a.add("125");
a.add("126");
// for(Object i : a){
// System.out.println(i);
// }
Iterator it = a.iterator();
while(it.hasNext()){
Object i = it.next();
System.out.println(i);
}
}

输出:

125
126
123
124

public static void testTreeSet(){
Set a = new TreeSet();
a.add("123");
a.add("124");
a.add("125");
a.add("126");
// for(Object i : a){
// System.out.println(i);
// }
Iterator it = a.iterator();
while(it.hasNext()){
Object i = it.next();
System.out.println(i);
}
}

输出:

123
124
125
126

public static void testTreeSet(){
Set a = new TreeSet();
a.add("124");
a.add("123");
a.add("125");
a.add("126");
// for(Object i : a){
// System.out.println(i);
// }
Iterator it = a.iterator();
while(it.hasNext()){
Object i = it.next();
System.out.println(i);
}
}

输出:

123
124
125
126