学习集合Collection_通用方法

Collection 常用接口

集合List和Set通用的方法

  • public boolean add(E e)     添加对象到集合

  • public boolean remove(E e)   删除指定元素

  • public void clear()       清空集合中元素

  • public boolean contains(E e)  判断是否包含元素

  • public boolean isEmpty()    判断当前集合是否为空

  • public int size()        返回集合中元素个数

  • public Object[] toArray()   把集合中元素存储到数组中

  • public boolean addAll(Collection<? extends E> c) 添加指定集合所有对象到集合

  • public boolean containsAll(Collection<?> c)判断是否包含指定集合中的所有元素

  • public boolean removeAll(Collection<?> c) 删除指定集合中包含的所有此集合的元素

Collection中有 public Iterator<E> iterator() 返回集合中元素的迭代器,用于遍历。
遍历方法,以后学习了Set再说,迭代器是抽象类常用的通用方法有:hasNext(),next(),remove();

使用方法

public class StudyCollection {

	public static void main(String[] args) {
		//集合创建支持多态写法
//		Collection<String> collect = new ArrayList<String>();
		//因为该部分方法通用,new其他的集合,以下方法一样适用
		Collection<String> collect = new HashSet<String>();
		System.out.println(collect);
		
		//add方法会返回结果true或false
		boolean result = collect.add("aaaa");
		System.out.println(collect+""+result);
		
		//用for循环添加元素进入来练习其他方法
		for (int i = 0; i < 10; i++) {
			String string = String.valueOf(i);
			collect.add(string);
		}
		
		if (collect.contains("aaaa")) {
			System.out.println("包含aaaa");
		}else {
			System.out.println("不包含aaaa");
		}
		
		System.out.println(collect);
		System.out.println(collect.size());
		System.out.println(collect.isEmpty());
		System.out.println(collect.remove("aaaa"));
		System.out.println(collect);
		
	}
}

输出结果

[]
[aaaa]true
包含aaaa
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, aaaa]
11
false
true
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


posted @ 2019-12-15 21:28  BuildFantasticDream  阅读(294)  评论(0)    收藏  举报