一、集合框架基本概念
集合是长度可变的用于存取数据的容器,可以存储不同类型的对象,存储的都是对象的引用(地址)。
二、集合框架基本分类
1、集合框架图解
2、基本分类
三、JAVA包装类
1、基本数据类型对应的包装类
int:Integer
byte: Byte
short:Short
long:Long
float:Float
double:Double
char:Character
boolean:Boolean
四、Collection接口
1、Collection接口基本概念
Collection接口定义了存取一组对象的方法,其子接口Set和List分别定义了存储方式。
2、Collection主要方法摘要
boolean add();
添加元素到 collectionvoid clear();
移除此 collection 中的所有元素boolean contains();
如果此 collection 包含指定的元素,则返回 trueboolean equals();
比较此 collection 与指定对象是否相等int hashCode();
返回此 collection 的哈希码值boolean isEmpty();
判断此 collection 是否为空Iterator<object> iterator();
返回在此 collection 的元素上进行迭代的迭代器boolean remove();
从此 collection 中移除指定元素的单个实例,如果存在的话int size();
返回此 collection 中的元素数Object[] toArray();
返回包含此 collection 中所有元素的数组
举例说明某些方法
public class CollectionDemo{
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("hello");
c.add(1);
c.add('a');
c.add(new Integer(100));
System.out.println("是否成功移除'a':" + c.remove('a'));
System.out.println("集合是否为空:" + c.isEmpty());
System.out.println("集合是否包含'helllo':" + c.contains("hello"));
System.out.println("集合数据有:" + c);
System.out.println("集合长度 = " + c.size());
//将集合转成String类型的数组并输出
Object[] array = c.toArray();
System.out.print("数组里面的元素有:");
for(Object i: array) {
System.out.print(i + " ");
}
c.clear(); //清空集合
System.out.println("\n集合中是否还有元素:" + c);
}
}
得到如下结果:
是否成功移除'a':true
集合是否为空:false
集合是否包含'helllo':true
集合数据有:[hello, 1, 100]
集合长度 = 3
数组里面的元素有:hello 1 100
集合中是否还有元素:[]
五、Iterator接口
1、基本概念
在上面示例中,利用System.out.println("集合数据有:" + c);
直接打印集合c
相当于调用了toString()
方法。除了这种方式外,Collection有其特有的输出方式:迭代器Iterator。
//获取迭代器
Iterator it = c.iterator();
System.out.println("利用迭代器iterator输出结果为:");
while(it.hasNext()) {
System.out.print(it.next() + " ");
}
//输出结果为
利用迭代器iterator输出结果为:hello 1 100
另外,也可以用for循环输出
System.out.print("利用迭代器iterator输出结果为:");
for(Iterator it = c.iterator(); it.hasNext(); ) {
System.out.print(it.next() + " ");
}
//输出结果同样为
利用迭代器iterator输出结果为:hello 1 100
所有实现了Collection接口的集合类都有一个Iterator方法,用于返回一个实现了Iterator接口的对象,Iterator对象称作迭代器,用以方便的实现对集合内元素的遍历操作。
2、Iterator主要方法摘要
boolean hasNext();
//判断游标右边是否还有元素Object next();
//返回游标右边的元素并将游标移动到下一个位置void remove();
//删除游标左面的元素,在执行完next()方法之后该操作只能执行一次