HashSet
HashSet对集合的迭代顺序不作任何保证
利用HashSet集合存储学生对象并遍历
学生类 有两个成员变量 ,无参有参构造方法,get and set方法,重写hashCode和equals方法
测试类
package com.Test01; import java.util.HashSet; public class HashSetDemo { public static void main(String[] args) { //创建HashSet集合对象 HashSet<Student> hc = new HashSet<>(); Student s1 = new Student("林一",25); Student s2 = new Student("张大彪",30); Student s3 = new Student("林云龙", 30); hc.add(s1);hc.add(s2);hc.add(s3); for(Student s:hc){ System.out.println(s.getName()+","+s.getAge()); } } }
package com.Test01; import java.util.LinkedHashSet; public class LinkedHashSetDemo { public static void main(String[] args) { LinkedHashSet<String> lk = new LinkedHashSet<>(); String s1 = "hello"; String s2 = "world"; String s3 = "java"; String s4 = "java"; lk.add(s1);lk.add(s2);lk.add(s3);lk.add(s4); for(String s:lk) { System.out.println(s); } } }
输出结构
hello
world
java