Collection中常用的方法
-
Collection中能存放什么元素?
没有使用泛型之前,Collection中可以存储Object的所有子类型。
使用了泛型之后,Collection中只能存储某个具体的类型。
(集合中不能直接存储基本数据类型,也不能存java对象,知识存储对象的内存地址)
-
Collection中的常用方法
-
boolean add(Object e) 向集合中添加元素
Collection c = new ArrayList(); c.add(1200); //自动装箱(java5 的新特性)。实际上是存进去了一个对象的内存地址 c.add(3.14); c.add(new Object()); c.add(new Student()); c.add(true);
-
int size() 获取集合中元素的个数 注意不是length
System.out.println("集合中元素的个数是:" + c.size());
-
void clear() 清空集合
c.clear(); System.out.println("集合中元素的个数是:" + c.size());//0
-
boolean contains(Object o) 如果此集合包含指定的元素,则返回 true 。
c.add("hello"); c.add("world"); c.add("hulk"); c.add("绿巨人"); System.out.println(c.contains("绿巨人")); //true
-
boolean remove(Object o) 从该集合中删除指定元素的单个实例(如果存在)(可选操作)。
System.out.println(c.remove("hulk"));//true System.out.println(c.remove(""));//false System.out.println("集合中元素的个数是:" + c.size());//3
-
boolean isEmpty() 如果此集合不包含元素,则返回 true 。
System.out.println(c.isEmpty());//false c.clear(); System.out.println(c.isEmpty());//true
-
Object[] toArray() 返回一个包含此集合中所有元素的数组。 可以把集合转换为数组(了解)
c.add("asd"); c.add("qwe"); c.add("wew"); c.add(100); c.add("helloworld!"); //转换成数组 Object[] objs = c.toArray(); for (int i = 0; i < objs.length; i++) { System.out.println(objs[i]); } /* asd qwe wew 100 helloworld! */
-