【LinkedList源码】LinkedList的构造方法源码及用法

1 LinkedList构造方法

LinkedList继承自AbstractSequentialList类,实现了List、Deque、Cloneable和Serializable接口。linkedList有两个构造方法,一个是无参构造方法,一个是有一个参数的构造方法。构造方法源码如下所示:

/**
     * Constructs an empty list.
     */
    public LinkedList() {
    }

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

如上所示,无参构造方法什么都没有。有参构造方法只有一个参数,参数类型是集合类。有参构造方法调用了无参构造方法,并调用了addAll方法。addAll方法的主要作用是:将指定集合的所有元素添加到当前列表的尾部,按照指定集合的顺序插入,如果在操作正在进行时修改指定的集合,则此操作的行为是不确定的。此处说明了LinkedList不是线程安全的。

2 LinkedList的用法

	public static void main(String[] args) {

		LinkedList<String> list = new LinkedList<>();
		list.add("1");
		list.add("2");
		list.add("3");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}

		System.out.println("------------分割线----------------");
		
		ArrayList<String> list2 = new ArrayList<>();
		list2.add("wo");
		list2.add("ni");
		list2.add("ta");
		
		LinkedList<String> list3 = new LinkedList<>(list2);
		for(int i=0;i<list3.size();i++){
			System.out.println(list3.get(i));
		}
	}

结果:

1
2
3
------------分割线----------------
wo
ni
ta

3 总结

LinkedList不是线程安全的,实现了List和Cloneable接口。

发布了107 篇原创文章 · 获赞 142 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/u013293125/article/details/97571413