#Thinking in Java阅读笔记# 第十一章 持有对象

Java容器类

基本类型分为collection类和Map类
colletion储存独立元素的序列,分为List/Set/Queue三个接口
Map又名映射类(关联数组),储存键值对对象
具体容器类只在创建容器类对象时使用,可以直接创建接口对象而方便改变具体类型

List<Integer> list = new ArraysList<>();

Arrays.asList()/Collection.addAll()/Collections.addAll()

Arrays.asList()接受一个数组或者用逗号分隔的元素列表,返回一个List对象,
用途:
1.直接构建List对象,注意,此时的List对象是固定宽度的,不支持删加
2.在创建collection类时作为参数传递,因为collection类可以接受另一个collection类初始化
Collection.addAll(Collection),某collection类将另一个collection类的元素添加到其中,它与其他两个方法相比比较局限,不能使用元素列表添加
Collections.addAll(Collection,数组/元素列表),调用静态方法Collections.addAll(),使得第一个参数加入后面参数的值
应用如下:

import java.util.*;
public class TestJava{
    public static void main(String[] args) {
        Integer[] a = {1,2,3,4,5};
        Collection <Integer> list = new ArrayList<>(Arrays.asList(a));//1.
        list.addAll(Arrays.asList(6,7,8,9,10));
        Collections.addAll(list,11,12,13,14,15);
        Collections.addAll(list,a);
        List<Integer> l = Arrays.asList(3,4,5,6);//2.
    }
}

注意:在使用Arrays.asList()生成List时,最好指定出转换类型

List<Type> l = Arrays.<Type>asList(....);

容器打印行为toString()

容器类均可以直接被Print()

import java.util.*;
public class TestJava{
    static Collection fill(Collection<String> c) { 
        c.add("one");
        c.add("two");
        c.add("three");
        c.add("four");
        c.add("three");
        return c;
    }
    static Map fill(Map<String,String> map) {
        map.put("one", "1");
        map.put("two", "2");
        map.put("three", "3");
        return map;
    }
    public static void main(String[] args) {
        System.out.println(fill(new ArrayList<String>()));
        System.out.println(fill(new LinkedList<String>()));
        System.out.println(fill(new HashSet<String>()));
        System.out.println(fill(new TreeSet<String>()));
        System.out.println(fill(new LinkedHashSet<String>()));
        System.out.println(fill(new HashMap<String,String>()));
        System.out.println(fill(new TreeMap<String,String>()));
        System.out.println(fill(new LinkedHashMap<String,String>()));
    }
}
结果如下:
[one, two, three, four, three]//ArrayList和LinkedList都是按照插入顺序储存元素
[one, two, three, four, three]
[four, one, two, three]//Set不保存重复元素,HashSet的获取速度最快,但是它无法保存元素的顺序
[four, one, three, two]//TreeSet按照元素的升续排列
[one, two, three, four]//LinkedHashSet按照插入顺序排列
{one=1, two=2, three=3}//Map保存键值对,HashMap的获取速度最快,但是它无法保存元素的顺序
{one=1, three=3, two=2}//TreeMap按照键的升续排列
{one=1, two=2, three=3}//LinkedHashMap按照插入顺序排列

List

ArrayList和LinkedList:ArrayList适合随机访问,不适用与多次插入和删除。而LinkedList相反

迭代器

所有容器类都有iterator()方法,它能够返回一个Iterator对象,这个对象能够单向的访问容器中的元素,能够使得遍历序列的操作与序列的底层结构分析
1.next()
2.hasNext()
3.remove()
所有的List类均有listIterator(),可以返回一个ListIterator对象,这种迭代器能够双向遍历序列

Stack

后进先出,可以用LinkedList直接作为栈使用

猜你喜欢

转载自blog.csdn.net/zhou373986278/article/details/78499970