集合(List、Set、Map)

List,Set是继承自Collection接口,Map不是

public interface List<E> extends Collection<E> {
public interface Set<E> extends Collection<E> {
public interface Map<K,V> {

详细介绍: 
List特点:元素有放入顺序,元素可重复 
Map特点:元素按键值对存储,无放入顺序 
Set特点:元素无放入顺序,元素不可重复(注意:元素虽然无放入顺序,但是元素在set中的位置是有该元素的HashCode决定的,其位置其实是固定的) 

public class ListTest {

    public static void main(String[] args) {
        ListTest.getList();
        ListTest.getSet();
        ListTest.getMap();
    }

    // ArrrayList:是非线程安全的,效率高;
    public static void getList() {
        System.out.println("===========List===============");
        List list = new ArrayList();
        list.add("a");
        list.add("d");
        list.add("c");
        list.add("a");
        list.add(null);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

    // hashset:为快速查找设计的Set
    public static void getSet() {
        System.out.println("===========Set===============");
        Set<String> set = new HashSet<String>();
        set.add("a");
        set.add("d");
        set.add("c");
        set.add("a");
        set.add(null);
        for (Object str : set) {
            System.out.println(str);

        }

    }

    // HashMap:非线程安全,高效,支持null
    public static void getMap() {
        System.out.println("===========Map===============");
        Map map = new HashMap<>();
        map.put("1", "5");
        map.put("1", "6");
        map.put(null, "5");
        map.put("2", "1");
        map.put("2", null);
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entity = (Map.Entry<String, String>) it.next();
            String key = entity.getKey();
            String value = entity.getValue();
            System.out.println("key:" + key + "       value:" + value);
        }

    }

}

 运行结果:

===========List===============
a
d
c
a
null
===========Set===============
null
a
c
d
===========Map===============
key:null       value:5
key:1       value:6
key:2       value:null

 

posted @ 2017-08-10 20:04  wujuan  阅读(155)  评论(0编辑  收藏  举报