容器
1 泛型
使代码能够适用于某种不具体的类型,通过实现“参数化类型”的手段。
#泛型的声明
class 类名 <E>{
}
#E可以代表其他任何类型,类或者接口,但是不能是基本类型
public class generic_v1 {
public static void main(String[] args) {
String s1 = "helloworld";
printobject p1 = new printobject(s1);
p1.print();
Rect r1 = new Rect(1,2);
printobject p2 = new printobject(r1);
p2.print();
}
}
class printobject{
private Object o;
public printobject(Object o){this.o = o;}
public void print(){
String str = o.toString();
System.out.println(str);
}
}
class Rect{
private int width;
private int height;
public Rect(int w , int h){
width = w;
height = h;
}
public String toString(){
return "宽"+width+"高"+height+"的矩形。";
}
}
public class generic_v2 {
public static void main(String[] args) {
String s1 = "helloworld";
printobject2 p1 = new printobject2(s1);
p1.print();
Rect r1 = new Rect(1,2);
printobject2 p2 = new printobject2(r1);
p2.print();
}
}
class printobject2 <E>{
private E o;
public printobject2(E o){this.o = o;}
public void print(){
System.out.println(o);
}
}
2 Collection
容器的作用是保存对象的引用
2.1 List
List是一个接口,实现List接口的所有类都可以认为是一个List.典型的List接口的实现类有ArrayList和LinkedList
st
List是一个接口,实现List接口的所有类都可以认为是一个List.典型的List接口的实现类有ArrayList和LinkedList