集合,集合是java中提供的一种容器,可以用来存储多个数据。
在前面的学习中,我们知道数据多了,可以使用数组存放或者使用ArrayList集合进行存放数据。那么,集合和数组既然都是容器,它们有啥区别呢?
数组的长度是固定的。集合的长度是可变的。集合中存储的元素必须是引用类型数据。
集合继承关系图
A:集合继承关系图
a:ArrayList的继承关系:
查看ArrayList类发现它继承了抽象类AbstractList同时实现接口List,而List接口又继承了Collection接口。Collection接口为最顶层集合接口了。
源代码:
interface List extends Collection {
}
public class ArrayList extends AbstractList implements List{
}
b:集合继承体系
这说明我们在使用ArrayList类时,该类已经把所有抽象方法进行了重写。那么,实现Collection接口的所有子类都会进行方法重写。
Collecton接口常用的子接口有:List接口、Set接口
List接口常用的子类有:ArrayList类、LinkedList类
Set接口常用的子类有:HashSet类、LinkedHashSet类
Collection 接口
|
----------------------------------------------------------------
| |
List接口 Set接口
| |
---------------- -------------
| | | |
ArrayList类 LinkedList类 HashSet类 LinkedHashSet类
泛型的引入
A:泛型的引入
在前面学习集合时,我们都知道集合中是可以存放任意对象的,
只要把对象存储集合后,那么这时他们都会被提升成Object类型。
当我们在取出每一个对象,并且进行相应的操作,这时必须采用类型转换。比如下面程序:
public class GenericDemo {
public static void main(String[] args) {
List list = new ArrayList();
list.add("abc");
list.add("itcast");
list.add(5);//由于集合没有做任何限定,任何类型都可以给其中存放
//相当于:Object obj=new Integer(5);
Iterator it = list.iterator();
while(it.hasNext()){
//需要打印每个字符串的长度,就要把迭代出来的对象转成String类型
String str = (String) it.next();//String str=(String)obj;
//编译时期仅检查语法错误,String是Object的儿子可以向下转型
//运行时期String str=(String)(new Integer(5))
//String与Integer没有父子关系所以转换失败
//程序在运行时发生了问题java.lang.ClassCastException
System.out.println(str.length());
}
}
}
/*
* JDK1.5 出现新的安全机制,保证程序的安全性
* 泛型: 指明了集合中存储数据的类型 <数据类型>
*/
public class GenericDemo {
public static void main(String[] args) {
function();
}
public static void function(){
Collection<String> coll = new ArrayList<String>();
coll.add("abc");
coll.add("rtyg");
coll.add("43rt5yhju");
// coll.add(1);
Iterator<String> it = coll.iterator();
while(it.hasNext()){
String s = it.next();
System.out.println(s.length());
}
}
}
泛型类:泛型的通配符
/*
* 泛型的通配符
*/
public class GenericDemo {
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<String>();
HashSet<Integer> set = new HashSet<Integer>();
array.add("123");
array.add("456");
set.add(789);
set.add(890);
iterator(array);
iterator(set);
}
/*
* 定义方法,可以同时迭代2个集合
* 参数: 怎么实现 , 不能写ArrayList,也不能写HashSet
* 参数: 或者共同实现的接口
* 泛型的通配,匹配所有的数据类型 ?
*/
public static void iterator(Collection<?> coll){
Iterator<?> it = coll.iterator();
while(it.hasNext()){
//it.next()获取的对象,什么类型
System.out.println(it.next());
}
}
}