Collection接口:
学习顶层Collection接口,学习其子类的共性方法,所有子类都可以使用。
定义了单列集合(List和Set)的一些通用方法,任意单列集合都可以使用Collection接口的方法。
1.共性的方法:
返回值为boolean类型的方法:
-
**add(E e)**方法 :
把当前对象添加到集合中。
返回值一般为布尔值,一般不接受返回值。
-
**remove(Object o)**方法 :
把当前对象在集合中删除。
如果元素存在,删除元素,返回true;如果元素不存在,删除失败,返回false。
-
isEmpty() 方法: 判断集合是否为空。
如果为空,返回true。否则,false。
-
**contains(Object o)**方法:
如果此集合包含指定的元素,则返回 true 。
返回值为int型的方法:
- **size()**方法:返回集合中元素的个数。
返回值为Object[]数组的方法:
- **toArray()**方法:把集合元素存储到数组中。
返回为空:
clear()方法:清空集合,但是不删除集合。
package setclass.Collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class CollectionDemo {
public static void main(String[] args) {
Collection<String> col=new ArrayList<>();//多态,接口指向实现类
//boolean 类型
// add方法
col.add("张三");
col.add("李四");
col.add("王五");
col.add("赵六");
System.out.println(col);//重写过toString方法
//contains方法
System.out.println("-----contains方法-----");
boolean b1 = col.contains("张三");
System.out.println("b1:"+b1);
boolean b2 = col.contains("zhangsan");
System.out.println("b2:"+b2);
//remove方法
System.out.println("----remove方法----");
boolean b3 = col.remove("张三");
System.out.println("b3是否移除:"+b3);
boolean b4 = col.remove("张五");
System.out.println("b4是否移除:"+b4);
//isEmpty方法
System.out.println("----isEmpty方法----");
boolean empty = col.isEmpty();
System.out.println(empty);
//size方法
System.out.println("----size方法----");
int size = col.size();
System.out.println("集合个数为:"+size);
//toArray方法
Object[] objects = col.toArray();
System.out.println(Arrays.toString(objects));
//clear方法
col.clear();
System.out.println(col.isEmpty());
}
}
集合:
[张三, 李四, 王五, 赵六]
-----contains方法-----
b1:true
b2:false
----remove方法----
b3是否移除:true
b4是否移除:false
----isEmpty方法----
false
----size方法----
集合个数为:3
[李四, 王五, 赵六]
true