集合
List
List接口的使用
public class Test {
public static void main(String[] args){
//添加数字类型的数据
List list = new ArrayList();
//在集合中添加数据时会自动装箱
list.add(20);//该数据已经变成引用类型
list.add(30);
list.add(40);
list.add(50);
list.add(60);
System.out.println(list.size());
System.out.println(list.toString());
//删除
list.remove(0);//删除角标0的元素
list.remove(new Integer(40));//将数据强转也能删除数据
System.out.println(list.toString());
//subList方法,子集合
List subList = list.subList(0,2);//含头不含尾
System.out.println(subList.toString());
}
}
List实现类
ArrayList
- 用数组的结构实现,查询快,增删慢
- 运行速率快,线程不安全
- 源码分析
默认容量大小DEFAULT_CAPACITY = 10;
存放元素的数组elementData
public class Test {
public static void main(String[] args){
ArrayList arrayList = new ArrayList();//实例化一个集合
//添加
Student s1 = new Student("张三",20);
Student s2 = new Student("李四",18);
Student s3 = new Student("王五",19);
Student s4 = new Student("赵六",22);
Student s5 = new Student("小明",20);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
arrayList.add(s4);
arrayList.add(s5);
System.out.println("-----------添加-------------");
System.out.println(arrayList.size());
System.out.println(arrayList.toString());
//删除
arrayList.remove(1);
System.out.println("-----------删除-------------");
System.out.println(arrayList.size());
System.out.println(arrayList.toString());
//遍历
Iterator it = arrayList.iterator();
System.out.println("-----------Iterator遍历-------------");
while ((it.hasNext())){
Student s =(Student) it.next();
System.out.println(s.toString());
}
//ListIterator可从前往后,也可从后往前遍历
ListIterator lit = arrayList.listIterator();
//从前往后遍历
System.out.println("-----------ListIterator前-------------");
while ((lit.hasNext())){
Student st =(Student) lit.next();
System.out.println(st.toString());
}
//从后往前遍历
System.out.println("-----------ListIterator后-------------");
while (lit.hasPrevious()){
Student stu = (Student) lit.previous();
System.out.println(stu.toString());
}
//判断
System.out.println(arrayList.contains(s1));
}
}
Vector
- 用数组的结构实现,查询快,增删慢
- 运行速率慢,线程安全
public class Test {
public static void main(String[] args){
Vector vector = new Vector();
//添加
vector.add("草莓");
vector.add("葡萄");
vector.add("桔子");
System.out.println(vector.size());
System.out.println(vector.toString());
//遍历 使用枚举器
Enumeration enu = vector.elements();
while (enu.hasMoreElements()){
String str = (String) enu.nextElement();
System.out.println(str);
}
}
}
LinkedList
public class Test {
public static void main(String[] args){
//创建集合
LinkedList linkedList = new LinkedList();
//添加
Student s1 = new Student("张三",20);
Student s2 = new Student("李四",18);
Student s3 = new Student("王五",19);
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
System.out.println(linkedList.size());
System.out.println(linkedList.toString());
//获取
System.out.println(linkedList.indexOf(s1));//获取某个数据的位置
}
}