特点:
有序重复,包括null,通过整数索引访问
实现类ArrayList和LinkedList
ArrayList--动态数组 不线程同步 单线程合适
List<String> nList=new ArrayList<String>(); nList.add("A"); nList.add("B"); nList.add("C"); nList.add(1, "D"); nList.set(2, "tanlei"); //使用迭代器进行统一遍历 Iterator<String> lists =nList.iterator(); while(lists.hasNext()) { String name=lists.next(); System.out.println(name); } //增强for循环遍历 for(String name : nList) { System.out.println(name); } System.out.println("********"); System.out.println(nList.indexOf("C"));//返回此元素的索引 System.out.println(nList.remove("tanlei"));//删除首次出现的元素 System.out.println(nList.size());//返回列表中的元素数 System.out.println(nList.contains("tanlei"));//c查询元素中是否包含 System.out.println(nList.get(1));//通过下标访问 System.out.println(nList.isEmpty());//判断里面是否有内容 nList.clear();//清空元素
package com.day1; import java.util.ArrayList; import java.util.List; public class ArrayListDemo2 { public static void main(String[] args) { List<Student> stulist=new ArrayList<Student>(); Student stu1=new Student("张三", 18); Student stu2=new Student("李四", 20); Student stu3=new Student("王五", 22); stulist.add(stu1); stulist.add(stu2); stulist.add(stu3); Student stu4=new Student("王五", 22); System.out.println(stulist.indexOf(stu4));//查找stu4王五的下标 根据自己重写的equals方法 System.out.println(stulist.contains(stu4));//容器包含stu4 System.out.println(stulist.remove(stu4));//删除stu4其实是删掉了与stu4相同内容的stu3 System.out.println(stulist.indexOf(stu3));//找不到 -1 System.out.println(stulist.size());//大小为2 } } class Student{ private String name; private int age; public Student(String name, int age) { 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 boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }