JAVA中的Collection的常用方法
- Collection中能存放什么元素:
没有使用“泛型”之前,Collection可以存储Object的所有子类
使用“泛型”之后,Collection中只能存储某个具体的类型 - Collection中的常用方法:
boolean .add(Object o) 向集合中添加元素
int .size() 获取集合中元素的个数
void .clear() 清空集合
boolean .contains(Object o) 判断当前集合中是否包含元素e
boolean .remove(Object o) 移除集合中的o元素
boolean .isEmpty() 判断集合中元素个数是否为0
Object[] toArray() 调用这个方法可以把集合转为数组
public class CollectionTest01 {
public static void main(String[] args) {
Collection e = new ArrayList();
e.add(120);
e.add("大威天龙");
e.add(true);
e.add(3.14);
System.out.println(e.size());
e.clear();
System.out.println(e.size());
e.add(120);
e.add("大威天龙");
e.add(true);
e.add(3.14);
System.out.println(e.contains("大威天龙"));
e.remove(120);
System.out.println(e.size());
System.out.println(e.isEmpty());
e.clear();
System.out.println(e.isEmpty());
e.add(120);
e.add("大威天龙");
e.add(true);
e.add(3.14);
e.add(new Student());
Object[] obj = e.toArray();
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i]);
}
}
}
class Student{
}
4
0
true
3
false
true
120
大威天龙
true
3.14
collection.Student@2f4d3709