List集合存储字符串并遍历
List集合存储字符串并遍历和Collection的一样上面有链接可以参考一下
/* List特点
* 有序(存储和取出的元素一致)可重复的
*
* */
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListDemo2 {
public static void main(String[] args) {
//创建集合对象
List list = new ArrayList();
//添加元素
list.add("hello");
list.add("world");
list.add("Java");
list.add("java");
list.add("hhh");
list.add("java");
list.add("hhh");
//遍历
Iterator it = list.iterator();
while(it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
}
}
}
输出结果为:
hello
world
Java
java
hhh
java
hhh
自定义存储遍历
先定义学生类
public class Student {
//成员变量
private String name;
private int age;
//构造方法
public Student() {
super();
// TODO Auto-generated constructor stub
}
//成员方法
public Student(String name, int age) {
super();
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;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
定义测试类
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListTest {
public static void main(String[] args) {
//创建集合对象
List list = new ArrayList();
//创建学生对象
Student s1 = new Student("张三",20);
Student s2 = new Student("李四",30);
Student s3 = new Student("王五",40);
Student s4 = new Student("赵六",18);
Student s5 = new Student("熊大",25);
Student s6 = new Student("熊二",23);
//将学生对象添加到集合对象中
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
list.add(s1);
list.add(s2);
list.add(s3);
//遍历
Iterator it = list.iterator();
while(it.hasNext()) {
Student s = (Student)it.next();
System.out.println(s.getName()+"----"+s.getAge());
}
}
}
输出结果为:
张三----20
李四----30
王五----40
赵六----18
熊大----25
熊二----23
张三----20
李四----30
王五----40