一、 Collection接口
特点:元素是Object
子接口: List 和 Set
常用方法:
add(Object o):把对象o放入集合
addAll(Collection c): 把c中的所有对象放入当前集合
clear():清空集合
contains(Object o): 判断对象o在集合中是否存在
isEmpty(): 判断集合是否为空
remove(Object o):把对象o从集合中删除
removeAll(Collection c)删掉集合c中所有对象
size():返回集合中对象的个数
toArray():把集合转换成数组返回
iterator():返回一个Iterator对象 迭代器
遍历: 迭代遍历
while(o.hasNext()){ //hasNext()指针右边没对象,返回false,有对象返回true
Object os = o.next();
System.out.println(os);
}
实现类:无
二、List接口:Collection的子接口
特点:元素有顺序(下标) 可以重复
常用方法:
add(int pos,Object o):把对象o插入到pos位置
get(int pos):返回pos位置的元素
indexOf(Obeject o):返回对象o在数组中的下标
remove(int pos):删除pos位置的元素
set(int pos,Object o):把pos位置的元素替换成o
遍历:
1.for 下标遍历
for(int i = 0;i < list.size();i++){
Object o = list.get(i);
System.out.println(o);
}
2.迭代遍历
实现类:
1.ArrayList 用数组实现 数组查询快,增删慢
jdk1.2版本 轻量级(运行速度快) 线程不安全
2.Vector 用数组实现
jdk1.0版本 重量级(运行速度慢) 线程安全
3.LinkedList 用链表实现 链表查询慢 增删快
一般是封装一个LinkedList对象作为Stack的属性来创建一个栈
public class Stack{
//封装一个LinkedList属性 为了方便使用LinkedList中的一些方法
private LinkedList<Object> list = new LinkedList<Object>();
//入栈
public void push(Object o){
list.addFirst(o);
}
//出栈
public Object pop(){
Object o = list.removeFirst();
return o;
}
}
三、Set接口:Collection的子接口
特点:元素无顺序 不可重复
方法:全部继承自Collection接口
遍历:迭代遍历
实现类:
HashSet
把自定义对象放入HashSet,为保证元素不重复 必须:
(1)覆盖hashCode() 保证相同对象返回相同的int
为了提高效率,尽量保证不同对象返回不同的int
public class Student{
private int age;
private String name;
/*
省略...
//构造方法
//get set方法
*/
@Override
public int hashCode(){
int prime = 31;
int result = 1;
result = prime*result + age;
result = prime*result + name==null?0:name.hashCode();
return result;
}
}
(2)覆盖equals() 保证相同对象返回true
TreeSet 实现了SortedSet接口(Set的子接口)
对元素自动排序 要求元素对象必须实现Comparable接口