s-day02-Collection接口常用方法
This commit is contained in:
@@ -1,10 +1,16 @@
|
||||
package com.inmind.collection01;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
|
||||
/*
|
||||
Collection 常用功能
|
||||
Collection是所有单列集合的父接口,因此在Collection中定义了单列集合(List和Set)通用的一些方法,这些方法可用于操作所有的单列集合。方法如下:
|
||||
|
||||
有2个子接口:List和Set
|
||||
|
||||
Collection接口的常用方法:
|
||||
public boolean add(E e): 把给定的对象添加到当前集合中 。
|
||||
public void clear() :清空集合中所有的元素。
|
||||
public boolean remove(E e): 把给定的对象在当前集合中删除。
|
||||
@@ -14,4 +20,43 @@ public int size(): 返回集合中元素的个数。
|
||||
public Object[] toArray(): 把集合中的元素,存储到数组中。
|
||||
*/
|
||||
public class Demo02 {
|
||||
public static void main(String[] args) {
|
||||
//单列的多态【编译看左边,运行看右边】
|
||||
Collection<String> cols = new ArrayList<>();
|
||||
//添加元素
|
||||
//public boolean add(E e): 把给定的对象添加到当前集合中
|
||||
cols.add("张三");
|
||||
cols.add("李四");
|
||||
cols.add("王五");
|
||||
System.out.println(cols);
|
||||
//清空集合
|
||||
//public void clear() :清空集合中所有的元素。
|
||||
/*cols.clear();
|
||||
System.out.println(cols);*/
|
||||
|
||||
//删除元素
|
||||
//public boolean remove(E e): 把给定的对象在当前集合中删除。
|
||||
boolean removeRes = cols.remove("张三1");
|
||||
System.out.println(removeRes);
|
||||
System.out.println(cols);
|
||||
|
||||
//判断元素是否在集合中
|
||||
//public boolean contains(E e): 判断当前集合中是否包含给定的对象。
|
||||
boolean containsRes = cols.contains("张三1");
|
||||
System.out.println("是否包含张三1:"+containsRes);
|
||||
|
||||
//集合是否为空(健壮性判断,如果集合为null或者没有内容,就不操作)
|
||||
//public boolean isEmpty(): 判断当前集合是否为空。
|
||||
//cols.clear();
|
||||
boolean emptyRes = cols.isEmpty();
|
||||
System.out.println("集合是否为空:"+emptyRes);
|
||||
|
||||
//获取集合的长度
|
||||
//public int size(): 返回集合中元素的个数。
|
||||
System.out.println("集合的长度:"+cols.size());
|
||||
|
||||
//将集合转为数组
|
||||
Object[] array = cols.toArray();
|
||||
System.out.println(Arrays.toString(array));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user