class Person{ private String name; private int age; public Person(String name,int age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class T { public static void main(String[] args) { //存放基本类型String Set<String> set = new HashSet<String>(); set.add("a"); set.add("c"); set.add("b"); /** * 迭代遍历 */ Iterator<String> ite = set.iterator(); while(ite.hasNext()){ System.out.println(ite.next()); } /** * for循环遍历 */ for(String str:set){ System.out.println(str); } //存放对象 Set<Person> sets = new HashSet<Person>(); sets.add(new Person("zhangsan",21)); sets.add(new Person("lisi",20)); sets.add(new Person("wangwu",22)); /** * 迭代遍历 */ Iterator<Person> i = sets.iterator(); while(i.hasNext()){ Person person = i.next(); System.out.println(person.getName()+","+person.getAge()); } /** * for循环遍历 */ for(Person per:sets){ System.out.println(per.getName()+","+per.getAge()); } } }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/14329.html