本篇来学习Collection这个接口的几个方法,通过代码来熟悉和了解基本的几个方法的使用。Collection作为单列集合的根类,我们以后要经常使用这些方法。
1.add(E e)
上面参数E e表示是泛型,也就是可以把任何对象作为参数传入。泛型,还没有学习到,后面再说,先来看看add()方法的使用。
package collection;
import java.util.ArrayList;
import java.util.Collection;
public class Demo2_Collection {
@SuppressWarnings({"rawtypes", "unchecked" }) // 不对原始类型检查,不加IDE上报黄色警告波浪线
public static void main(String[] args) {
Collection c = new ArrayList();
boolean b = c.add("abc");
boolean b1 = c.add(100); //自动装箱处理,new Integer(100)
boolean b2 = c.add(true); //自动装箱处理,等同于new Boolean(true)
boolean b3 = c.add(new Student("张三",23));
System.out.println(b);
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println(c);
}
}
打印结果:
true
true
true
[abc, 100, true, Student [name=张三, age=23]]
其实在使用了add方法,由于它支持任意对象作为参数传入,而且ArrayList底层是基于数组实现,可以存储重复的元素,所以add方法的返回值,永远都是True。但是后面我们介绍的HashSet是不允许存储重复元素,使用add添加重复元素就会返回false。
2.remove(Object c)
上面add是添加方法,remove()字面意思也能看出来是删除方法。
package collection;
import java.util.ArrayList;
import java.util.Collection;
public class Demo2_Collection {
@SuppressWarnings({"rawtypes", "unchecked" })
public static void main(String[] args) {
Collection c = new ArrayList();
c.add('a');
c.add('b');
c.add('c');
c.add('d');
c.remove('b');
System.out.println(c);
}
}
输出:[a, c, d]
3.clear()
把集合里面元素清空的方法
package collection;
import java.util.ArrayList;
import java.util.Collection;
public class Demo2_Collection {
@SuppressWarnings({"rawtypes", "unchecked" })
public static void main(String[] args) {
Collection c = new ArrayList();
c.add('a');
c.add('b');
c.add('c');
c.add('d');
c.clear();
System.out.println(c);
}
}
输出:[]
4.contains()
判断集合中是否包含某一个对象的方法,返回值是布尔型
package collection;
import java.util.ArrayList;
import java.util.Collection;
public class Demo2_Collection {
@SuppressWarnings({"rawtypes", "unchecked" })
public static void main(String[] args) {
Collection c = new ArrayList();
c.add('a');
c.add('b');
c.add('c');
c.add('d');
boolean b = c.contains('c');
boolean b1 = c.contains('f');
System.out.println(b);
System.out.println(b1);
}
}
输出:
true
false
5.isEmpty()
判断集合是否为空
package collection;
import java.util.ArrayList;
import java.util.Collection;
public class Demo2_Collection {
@SuppressWarnings({"rawtypes", "unchecked" })
public static void main(String[] args) {
Collection c = new ArrayList();
c.add('a');
c.add('b');
c.add('c');
c.add('d');
System.out.println(c.isEmpty());
}
}
输出:false
6.size()
表示集合元素的个数,类似数组的length
import java.util.ArrayList;
import java.util.Collection;
public class Demo2_Collection {
@SuppressWarnings({"rawtypes", "unchecked" })
public static void main(String[] args) {
Collection c = new ArrayList();
c.add('a');
c.add('b');
c.add('c');
c.add('d');
System.out.println(c.size());
}
}
输出:4
到这里,我们学习了Collection接口的几个简单的方法,add()是添加到集合里,remove()是删除元素,clear()是清空集合,isEmpty()是判断集合是否为空,contains()是判断是否包含某一对象,集合的元素个数用size()方法。