一、Collection常用方法
Collection coll = new ArrayList();
1.add(Object obj)
添加元素对象到当前集合中
//add()
coll.add("AA");
coll.add("AA");
coll.add(new Person("Tom",12));
coll.add(128);//自动装箱
2.addAll(Collection other)
添加other集合中的所有元素对象到当前集合中,即this = this U other
//addAll(Collection other)
Collection coll1 = new ArrayList();
coll1.add("BB");
coll1.add(456);
coll.addAll(coll1);
coll.add(coll1);
注意事项:add(集合)也可以运行,但增加的是这个集合对象,不是集合里的元素
3.clear()
清空集合元素
coll.clear();
4.isEmpty()
判断当前集合是否为空集合
5.size()
获取当前集合中实际存储的元素个数
6.contains(Object obj)
判断当前集合中是否存在一个与obj对象equals返回true的元素
7.containsAll(Collection coll)
判断coll集合中的元素是否在当前集合中都存在。即coll集合是否是当前集合的“子集”
8.remove(Object obj)
从当前集合中删除第一个找到的与obj对象equals返回true的元素。
9.removeAll(Collection coll)
从当前集合中删除所有与coll集合中相同的元素。即this = this - this ∩ coll
10.hashCode()
获取集合对象的哈希值
11.equals()
判断当前集合与obj是否相等
12.toArray()
返回包含当前集合中所有元素的数组
13.iterator()
返回迭代器对象,用于集合遍历
注意:像collection添加元素的时候,要求所属的磊一定要重写equals()方法!
因为Collection中的相关方法(比如:contains() / remove())在使用时,要调用元素所在类的equals方法
二、List常用方法
List list = new ArrayList();
增:
add(Object obj)
list.add("AA");
list.add(123);
list.add(new Person("Tom",12));
addAll(Collection coll)
List list1 = Arrays.asList(1, 2, 3);
list.addAll(1,list1);
删
remove(Object obj)
List list = new ArrayList();
//add(Object obj)
list.add("AA");
list.add("BB");
list.add(123);//自动装箱
list.add(2);//自动装箱
list.add(new Person("Tom",12));
//删除索引2的元素
//list.remove(2);
//System.out.println(list);
//System.out.println(list.get(2));
//删除数据2
list.remove(Integer.valueOf(2));
System.out.println(list);
remove(int index)
改
set(int index,Object ele)
查
get(int index)
插
add(int index, Object ele)
addAll(int index, Collection eles)
长度
size()
遍历
iterator():使用迭代器进行遍历
Iterator iterator = list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
增强for循环
for(Object obj: list){
System.out.println(obj);
}
一般的for循环
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}