Java学习----集合函数

1.List----有序的collection(序列)

与数组的不同:数据类型可以相同可以不同,数组的长度是预先定义好的,集合的长度也是预先定义好的,但是长度会随着元素的增加而增加

ArrayList

LinkedList

Vector

public class ListTest {
    
    public static void main(String[] args) {
        //ArrayList arrayList = new ArrayList();
        //LinkedList arrayList = new LinkedList();
        Vector arrayList = new Vector(1,1);
        arrayList.add(10);
        arrayList.add("hello");
        
        
        // 便利序列的元素
        int size = arrayList.size();
        for (int i = 0; i < size; i++) {
            System.out.println(arrayList.get(i));
        }
    }
}
10
hello

2.Set---- 不包含重复出现的collection(元素无顺序,不可以重复)

public class SetTest {

    public static void main(String[] args) {
        //TreeSet treeSet = new TreeSet(); //二叉树实现
        HashSet treeSet = new HashSet(); // 哈希表实现
        treeSet.add(10);
        treeSet.add(7);
        treeSet.add(1);
        
        // 遍历集合
        Iterator iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            System.out.println(obj);
        }
        
    }
}
1
7
10

3.Map

Map也属于集合系统,但和Collection接口不同,Map是key对value的映射集合,其中key列就是一个集合。key不能重复,但是value可以重复。

HashMap,TreeMap(有序),Hashtable是三个主要的实现类。

public class MapTest {

    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put("s001", "aaa");
        map.put("s001", "bbb");
        map.put("s002", "ccc");
        
        System.out.println(map.size());
        System.out.println(map.get("s001")); // 同一个key有两个值,后面的会覆盖前面的那个
        System.out.println(map.get("s002"));
    }
}
2
bbb
ccc
原文地址:https://www.cnblogs.com/dragon1013/p/5128820.html