您的位置:首页 > 编程语言 > Java开发

java学习日记_80:集合框架之ArrayList

2016-11-17 10:44 483 查看
ArrayList继承了List和Collection。所以它所有的方法都是可以使用List和Collection里面的。

它没有什么特殊的方法,所以就不讲太多了,就直接来两个练习算了:

练习一:遍历

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListDemo {
public static void main(String[] args) {
// 创建集合对象
ArrayList array = new ArrayList();

// 创建元素对象,并添加元素
array.add("hello");
array.add("world");
array.add("java");

// 遍历
Iterator it = array.iterator();
while (it.hasNext()) {
String s = (String) it.next();
System.out.println(s);
}

System.out.println("-----------");

for (int x = 0; x < array.size(); x++) {
String s = (String) array.get(x);
System.out.println(s);
}
}
}


练习二:对自定义对象进行遍历
import java.util.ArrayList;
import java.util.Iterator;

/*
* ArrayList存储自定义对象并遍历
*/
public class ArrayListDemo2 {
public static void main(String[] args) {
// 创建集合对象
ArrayList array = new ArrayList();

// 创建学生对象
Student s1 = new Student("武松", 30);
Student s2 = new Student("鲁智深", 40);
Student s3 = new Student("林冲", 36);
Student s4 = new Student("杨志", 38);

// 添加元素
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);

// 遍历
Iterator it = array.iterator();
while (it.hasNext()) {
Student s = (Student) it.next();
System.out.println(s.getName() + "---" + s.getAge());
}

System.out.println("----------------");

for (int x = 0; x < array.size(); x++) {
// ClassCastException 注意,千万要搞清楚类型
// String s = (String) array.get(x);
// System.out.println(s);

Student s = (Student) array.get(x);
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
对应子类:

public class Student {
private String name;
private int age;

public Student() {
super();
}

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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: