Collection

一、集合的遍历

package com.huawei.test;

import java.util.ArrayList;
import java.util.Iterator;

public class Collection
{
    public static void traverse()
    {
        java.util.Collection<string> c = new ArrayList<string>();
        c.add("a");
        c.add("b");
        
        //遍历集合方式1:Iterator 
        //Note that Iterator.remove is the only safe way to modify a collection during iteration
        for (Iterator<string> it = c.iterator(); it.hasNext();)
        {
            if ("a".equals(it.next()))
            {
                it.remove();
            }
        }
        
        //遍历集合方式2:for each
        for (String s : c)
        {
            System.out.println(s);
        }
        
    }
    
    public static void main(String[] args)
    {
        traverse();
    }
}


运行结果
b

注意:
Use Iterator instead of the for-each construct when you need to:
•Remove the current element. The for-each construct hides the iterator, so you cannot call remove. Therefore, the for-each construct is not usable for filtering.
•Iterate over multiple collections in parallel.



二、集合的批量操作:
•containsAll — returns true if the target Collection contains all of the elements in the specified Collection.
集合包含
•addAll — adds all of the elements in the specified Collection to the target Collection.
并集
•removeAll — removes from the target Collection all of its elements that are also contained in the specified Collection.
删除交集
•retainAll — removes from the target Collection all its elements that are not also contained in the specified Collection. That is, it retains only those elements in the target Collection that are also contained in the specified Collection.
只保留交集
•clear — removes all elements from the Collection.
清空集合

eg:删除集合中的所有null元素
c.removeAll(Collections.singleton(null));



三、集合与数组的转换

Object[] a = c.toArray();
String[] a = c.toArray(new String[0]);//集合c中所有元素都是String</string></string></string>

你可能感兴趣的:(java,Collection)