Java-Conllection(容器)
容器的长度可以变化。
Collection(I)
Set(I) List(I)
HashSet(C) ArrayList(I) LinkedList(C)
Set(集合):无序(无索引),唯一
List(列表):有序,可重复
List比Set多了索引,在指定位置插入数据,查找指定索引上的数据,删除指定索引上的数据,替换索引上的数据。
ArrayList:查快改慢
LinkedList:改快查慢
容器迭代器
容器的迭代必须使用迭代器完成
Iterator接口
每个实现了Collection接口的类都能通过iterator方法来获得此容器的迭代器。
只有Iterator中的remove方法才是迭代过程中最安全的删除方法,因为加了锁。
Java5.0新特性
增强的for循环,就是.net中的forEach;
增强的for循环再迭代容器的时候内部依然使用迭代器
增强的for循环只能用来做简单的遍历
Java5.0新特性(泛型)
1.普通的容器可以放任意的数据类型,没有意义。
2.在拿容器元素的时候都是object,要向下转型。
import java.uitl.*; public class Test { public staric void main(String[] args) thows Exception{ List<String> List = new ArrayList<String>(); list.add("aaaa"); list.add("hello"); list.add("abc"); list.add("ccc"); String str = list.get(1); } }
Collections类
提供了一系列的方法对List进行操作
import java.util.*;
public class Tset {
public static void main(String args[]) {
List<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(2);
list.add(5);
list.add(4);
list.add(6);
for(int n:list){
System.out.print(n+ " ");
}
System.out.println();
Collections.sort(list); //排序
for(int n:list){
System.out.print(n+ " ");
}
}
}
Comparable接口
一个类的对象如果需要比较大小顺序,必须实现此接口
public class Test{ public static void main(String[] args){ List<Person> list = new ArrayList<Person>(); list.add(new Person("Tom",19)); list.add(new Person("Jack",29)); list.add(new Person("Rose",13)); list.add(new Person("Arron",69)); Collections.sort(list); for(Person p:list){ System.out.println(p); } } } class Person implements Comparable { public Person(String name,int age){ this.name = name; this.age = age; } String name; int age; public String toString(){ return "name:"+name+" age:"+age; } //判断一个对象是否是一个类或这个类子类的对象 public int compareTo(Object o){ if(o instanceof Object){ p = (Person)o; if(this.age > p.age){ return 1; }else if(this.age<p.age){ return -1; }else{ return 0; } }else{ return -1; } } }
自定义泛型
泛型不存在父类引用指向子类对象
public class Test{ public static void main(String[] args){ List<Integer> list1 = new ArrayList<Integer>(); list.add(1); list.add(20); List<Double> list2 = new ArrayList<Double>(); list.add(1.1)); list.add(new Person(20.1); Collections.sort(list); m(list1); m(list2); } //自定义了一种类型,这个类型名字叫T //在当前方法中出现的T,只要数据类型保持一致就可以了 public static <T> void m(List<T> list){ for(T i:list){ System.out.println(i); } } }

浙公网安备 33010602011771号