java----集合框架:
1,集合(容器):一个对象,用来储存其他多个对象,例如 ArrayList 类 或 数组;
2,ArrayList 类 代替 数组;
3,1)Collection :
它是一个接口,元素是Object;
方法:add(Object o):把对象o放入集合
addAll(Collection c):把c中的所有对象放入集合
clear():清空集合
contains(Object o):判断对象o在集合中是否存在
isEmpty():判断集合是否为空
remove(Object o):把对象o从集合中删去
size():返回集合中对象的个数
遍历:
实现类:无直接实现类
List :特点:元素有顺序(下标),可以重复;
方法:所有Collection的方法+自身和下标有关系的方法如下
add(int pos,Object o):把对象o插入到pos位置
get(int pos):返回pos位置的元素
indexOf(Object o):返回对象o在数组中的下标
remove(int pos):删除pos位置的元素
set(int pos,Object o):把pos位置的元素替换为o
遍历:下标遍历
利用迭代器 Iterator it=con.iterator(); ,迭代遍历
static void print(Collection con){
Iterator it=con.iterator();
while(it.hasNext()){
Object o= it.next();
system.out.println(o);
}
}
实现类:1,ArrayList:用数组实现(List) 1.2 轻量级 线程不安全 查询快 增删慢
2,Vector : 用数组实现 1.0 重量级 线程安全
3,LinkedList:用链表实现 查询慢 增删快(应用于"栈")
4,由于java.util.Stack 是java专用栈实现类,但是由于设计错误它不应该继承
vector父类,因为vector是数组实现,其中有add方法等,而对于栈操作而言
它最应该是链表实现,要有pop和push 方法,在实际中 Stack 继承了太多
无用的vector的方法
导致现在我们最好要自己写一个 Stack 类来自己用,代码如下:
class Stack{
private LinkedList list=new LinkedList();
public void push(Object o){
list.addFirst(o);
}
public Object pop(){
Object o=list.removeFirst();
return o;
}
}
Set :元素无顺序,内容不可重复:
实现类:1. HashSet :把自定义对象放入HashSet,为保证元素不重复,必须:
1) 覆盖hashCode() 保证相同对象返回相同的int,
提高效率考虑,尽量保证不同对象返回不同的int;
public int hashCode(){
return age+name.hasCode();
}
2) 覆盖equals() 保证相同对象返回 true;
(中有hashcode 用code来判断插到数组哪里,
当code值%数组长度 的值和之前的相同,调用equals,
判断内容是否相同,相同不加,不同放在数组下一个位置)
public int hashCode(){
return age; // 或是 return age+name.hasCode();
}
2. TreeSet 实现了 SortedSet (Set的子接口)
TreeSet 对元素自动排序,要求元素对象必须实现Comparable 接口;
遍历:利用迭代器 Iterator it=con.iterator(); ,迭代遍历
static void print(Collection con){
Iterator it=set.iterator();
while(it.hasNext()){
Object o= it.next();
system.out.println(o);
}
}
Collection<E>中的E是泛型