List接口的子类
【Java基础】集合框架
【Java基础】Collection子接口:List
ArrayList
- 底层数据结构是数组,查询快,增删慢;
- 线程不安全,效率高;
ArrayList的案例
1、存储字符串并遍历
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo1 {
public static void main(String[] args) {
//创建集合对象
ArrayList<String> array = new ArrayList<String>();
//把字符串添加到集合
array.add("hello");
array.add("world");
array.add("java");
//遍历集合
for (int i = 0; i < array.size(); i++) {
String s = array.get(i);
System.out.println(s);
}
}
}
2、存储自定义对象并遍历
//定义学生类Student-->省略
//测试类:
import java.util.ArrayList;
import java.util.Iterator;
class ArrayListDemo2 {
public static void main(String[] args) {
//创建集合对象
ArrayList<Student> array = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("张三", 18);
Student s2 = new Student("李四", 20);
Student s3 = new Student("王五", 22);
Student s4 = new Student("赵六", 24);
//把学生添加到集合
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
//遍历集合
Iterator<Student> it = array.iterator();
while (it.hasNext()) {
Student s = it.next();
System.out.println(s.getName() + "," + s.getAge());
}
}
}
ArrayList的练习
1、去除集合中字符串的重复值(字符串的内容相同)
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListTest1 {
public static void main(String[] args) {
//创建集合对象
ArrayList<String> array = new ArrayList<String>();
//添加多个字符串元素(包含内容相同的)
array.add("hello");
array.add("world");
array.add("world");
array.add("world");
array.