18.set集合:
①遍历:
public static void main(String[] args) {
Set<StudentTest> s = new HashSet<StudentTest>();
s.add(new StudentTest("1","张三"));
s.add(new StudentTest("2","李四"));
//遍历Set集合
//第一种方式:使用迭代器
Iterator it=s.iterator();
while(it.hasNext()){//hasNext判断有没有下一个元素
StudentTest sss=(StudentTest) it.next();//返回迭代的下一个元素
System.out.println(sss.getStuno()+" "+sss.getName());
}
//第二种方式:使用for each
//for each 方式本质还是迭代器 每循环一次 放的就是当前对象的地址 适合List Set Map
for(StudentTest ss:s){
System.out.println(ss.getName());
}
//第三种方式:将set集合转换成数组,存放的是StudentTest
Object[] o=s.toArray();
for(int i=0;i<o.length;i++){
StudentTest sssss=(StudentTest) o[i];
System.out.println(sssss.getName());
}
for(Object st:o){
System.out.println(st);
}
}
②Set集合元素不重复:
public static void main(String[] args) {
Set<StudentTest> s = new HashSet<StudentTest>();
StudentTest stu2 =new StudentTest();
stu2.setStuno("11");
stu2.setName("11");
s.add(stu2);
stu2.setStuno("12");
stu2.setName("12");
s.add(stu2);
System.out.println(s);
//重新new
stu2 =new StudentTest();
stu2.setStuno("13");
stu2.setName("13");
s.add(stu2);
System.out.println(s);
}
结果:[12 12]
[12 12, 13 13]
程序中向s中添加了两次,但实际s中只有一个,stu2只new了一次,两次添加的是同一个元素,
所以结果只有一个;当重新new时,就添加了。
java基础知识(七)
最新推荐文章于 2022-08-21 13:48:53 发布