List、Set、Map的foreach与迭代
程序员文章站
2022-03-21 20:39:32
...
List
有序且不唯一
public static void main(String[] args) {
List<Person> list=new ArrayList<Person>();
Person p1=new Person("LL", 12, "Beijing");
Person p2=new Person("KK", 22, "Shanghai");
Person p3=new Person("JJ", 32, "Wuhan");
list.add(p1);
list.add(p2);
list.add(p3);
for (Person p : list) {
System.out.println(p.toString());
}
Iterator<Person> ir=list.iterator();
while(ir.hasNext()){
Person p=ir.next();
System.out.println(p.toString());
}
}
运行结果 Person [Name=LL, Age=12, Address=Beijing]
Person [Name=KK, Age=22, Address=Shanghai]
Person [Name=JJ, Age=32, Address=Wuhan]
Person [Name=LL, Age=12, Address=Beijing]
Person [Name=KK, Age=22, Address=Shanghai]
Person [Name=JJ, Age=32, Address=Wuhan]
Set
无序且唯一
public static void main(String[] args) {
Set<Person> set=new HashSet<Person>();
Person p1=new Person("LL", 12, "Beijing");
Person p2=new Person("KK", 22, "Shanghai");
Person p3=new Person("JJ", 32, "Wuhan");
set.add(p1);
set.add(p2);
set.add(p3);
for (Person p : set) {
System.out.println(p.toString());
}
Iterator<Person> ir=set.iterator();
while(ir.hasNext()){
Person p=ir.next();
System.out.println(p.toString());
}
}
Person [Name=JJ, Age=32, Address=Wuhan]
Person [Name=LL, Age=12, Address=Beijing]
Person [Name=KK, Age=22, Address=Shanghai]
Person [Name=JJ, Age=32, Address=Wuhan]
Person [Name=LL, Age=12, Address=Beijing]
Person [Name=KK, Age=22, Address=Shanghai]