import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListTest { public static void main(String[] args) { List<Person> list = new ArrayList<>(); Person p1 = new Person("zhouyu", 22, "jiangsu"); Person p2 = new Person("liubei", 33, "sichuan"); Person p3 = new Person("caocao", 44, "henan"); list.add(p1); list.add(p2); list.add(p3); Iterator<Person> iterator = list.iterator(); // 方式1 迭代器 while (iterator.hasNext()) { Person person = iterator.next(); System.out.println(person); } System.out.println("-+_+_+_+_+_+_+_-"); // 方式2 普通for for (int i = 0; i < list.size(); i++) { Person person = (Person) list.get(i); System.out.println(person); } System.out.println("-+_+_+_+_+_+_+_-"); // 方式3 增强for for (Object object : list) { Person person = (Person) object; System.out.println(person); } System.out.println("-+_+_+_+_+_+_+_-"); Person person = new Person("zhangsan", 23, "zhangcun"); // 列表的修改功能 list.set(2, person); // 自带的toString方法 System.out.println(list.toString()); System.out.println("-+_+_+_+_+_+_+_-"); // 列表的截取功能 从指定位置开始截取到指定位置结束 System.out.println(list.subList(1, 3)); // [Person [name=liubei, age=33, address=sichuan], Person // [name=zhangsan, age=23, address=zhangcun]] // 获取指定索引 的元素 System.out.println(list.get(0)); } }
package cn.spring01.ArrayList; public class Person { private String name; private int age; private String address; @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", address=" + address + "]"; } 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 String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Person(String name, int age, String address) { super(); this.name = name; this.age = age; this.address = address; } }
Person [name=zhouyu, age=22, address=jiangsu]
Person [name=liubei, age=33, address=sichuan]
Person [name=caocao, age=44, address=henan]
-+_+_+_+_+_+_+_-
Person [name=zhouyu, age=22, address=jiangsu]
Person [name=liubei, age=33, address=sichuan]
Person [name=caocao, age=44, address=henan]
-+_+_+_+_+_+_+_-
Person [name=zhouyu, age=22, address=jiangsu]
Person [name=liubei, age=33, address=sichuan]
Person [name=caocao, age=44, address=henan]
-+_+_+_+_+_+_+_-
[Person [name=zhouyu, age=22, address=jiangsu], Person [name=liubei, age=33, address=sichuan], Person [name=zhangsan, age=23, address=zhangcun]]
-+_+_+_+_+_+_+_-
[Person [name=liubei, age=33, address=sichuan], Person [name=zhangsan, age=23, address=zhangcun]]
Person [name=zhouyu, age=22, address=jiangsu]