简体   繁体   English

Java通用集合

[英]Java generic collections

I start learning the Java generic collection using Deitel Harvey book - but I am facing a difficulty understanding the three line of codes below - Do all of them perform the same operation on by intializing and adding the relevant values of array ( colors ) to the LinkList variable (list1). 我开始使用Deitel Harvey的书来学习Java泛型集合 - 但我面临着理解下面三行代码的困难 - 所有这些代码都通过初始化并将相关的数组值(颜色)添加到LinkList来执行相同的操作变量(list1)。 How does the second method and third method works - I am having a bit difficulty understanding how Arrays can viewed as a list.. As I know arrays are not dynamic data structure, they have fixed sized length, adding/ removing elements on array can not be done on running time comparing to Lists in general. 第二种方法和第三种方法是如何工作的 - 我有点难以理解Arrays如何被视为一个列表..我知道数组不是动态数据结构,它们有固定大小的长度,在数组上添加/删除元素不能与一般的列表相比,可以在运行时间上完成。

String[] colors = { "black", "white", "blue", "cyan" };
List< String > list1 = new LinkedList< String >();

// method 1 of initalizing and adding elments to the list
for (String color : colors)
    list1.add(color);

// method 2 of initializing and adding elements to the list
List< String > list1 = new LinkedList< String > (Arrays.asList(colors));

// method 3 of initializing and adding elements to the list
List< String > list1 = Arrays.asList(colors);

Please help me understand my queries above, don't judge me as I am still new to this. 请帮助我理解我上面的疑问,不要评判我,因为我还是新手。 Thank you, Sinan 谢谢,思南

Actually knowledge of generics is not necessary for answering this question. 实际上,对于回答这个问题,没有必要了解泛型。

As you correctly identifier arrays are static in the sense that you can't add elements to them or remove them. 正确识别标识符数组是静态的,因为您无法向其添加元素或删除它们。

Lists , however, usually allow those operations. 但是, 列表通常允许这些操作。

The List returned by Arrays.asList() does have the add / remove methods (otherwise it would not be a valid List ). Arrays.asList()返回的List 确实add / remove方法(否则它不是有效的List )。 However actually calling those methods will throw an UnsupportedOperationException exactly because you can't actually add elements to an array (for which this List is simply a view/wrapper). 但是,实际调用这些方法将完全抛出UnsupportedOperationException 因为您无法实际向元素添加元素(此List只是一个视图/包装器)。

Operations that don't structurally modify the list (ie that don't change the number of elements in the list) are entirely possible: set(int, E) works just fine on the List returned by Arrays.asList() . 不在结构上修改列表的操作(即不改变列表中元素数量的操作)是完全可能的: set(int, E)Arrays.asList()返回的List上运行正常。

Arrays.asList returns a fixed-size list backed by the specified array. Arrays.asList返回由指定数组支持的固定大小的列表。

It is actually a bridge between Array and Collection framework. 它实际上是Array和Collection框架之间的桥梁。 But returned list write through to the array. 但返回列表写入数组。

Only your first method does anything to the LinkedList you have initially assigned into list1 . 只有您的第一个方法对您最初分配到list1LinkedList执行任何操作。 The other two assign a new, unrelated list to it. 另外两个为它分配一个新的,不相关的列表。 The third option assigns something that isn't a LinkedList , but a special implementation of the List interface backed by your String array. 第三个选项指定的东西不是LinkedList ,而是由String数组支持的List接口的特殊实现。 In the third case you won't be able to add/remove elements from the list, but you can iterate over it and update existing slots. 在第三种情况下,您将无法在列表中添加/删除元素,但您可以迭代它并更新现有的插槽。 Basically, it does what a plain array does, just through the List interface. 基本上,它只通过List接口执行普通数组的功能。

Arrays.asList creates a List from an Array. Arrays.asList从Array创建List。 Arrays in general can't be viewed as lists in Java. 通常,数组不能被视为Java中的列表。 They can only be wrapped in a list. 它们只能包含在列表中。

So method 2 is used to have a specific list implementation LinkedList in this case. 因此,在这种情况下,方法2用于具有特定的列表实现LinkedList

to Method 2, just check the Api here: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList(java.util.Collection ) For sure, Lists implement the Collections Interface so this Constructor will work here. 方法2,只需检查Api: http//docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList(java.util.Collection )肯定,列表实现集合接口,以便此构造函数在此处工作。

to Method 3, just check out the Api here: http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T ...) 方法3,只需在这里查看Api: http//docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList(T ...)

Every time you are interested in implementation you can look into certain method. 每当您对实施感兴趣时,您都可以研究某种方法。 For example, by press Ctrl+left mouse button onto method or class. 例如,通过按Ctrl +鼠标左键进入方法或类。

// method 2 of initializing and adding elements to the list
List<String> list1 = new LinkedList<String> (Arrays.asList(colors));

This code leads to: 此代码导致:

List<String> list1 = new LinkedList<String> (new ArrayList<String>(colors));

In constructor of ArrayList : ArrayList构造函数中:

ArrayList(E[] array) {
            if (array==null)
                throw new NullPointerException();
        a = array;
    }

the actual array is copied to encapsulated private array field( link is copied ). 将实际数组复制到封装的私有数组字段( 链接被复制 )。

Then in constructor of LinkedList : 然后在LinkedList构造函数中:

public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
    }

Every element of passed collection is added to the LinkedList . 传递集合的每个元素都将添加到LinkedList

if you see the link below http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList%28java.util.Collection%29 如果您看到以下链接http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html#LinkedList%28java.util.Collection%29

you will see the constructor of linked list class which is accepting a collection object as parameter. 您将看到链接列表类的构造函数,它接受集合对象作为参数。

Any in your post, the 2nd and 3 rd lines are passing an object of collection class(ie Arrays.asList is finally giving a List which is a sub class of collection). 在你的帖子中,第2行和第3行都传递了一个集合类的对象(即Arrays.asList最终给出了一个List,它是一个集合的子类)。

So both 2nd and 3rd lines fairly valid implementations. 所以第二和第三行都是相当有效的实现。 More over you can observe one more good coding practice in all the 3 lines. 更重要的是,你可以在所有3行中观察到一个更好的编码实践。 That is 那是

writing code to interceptors than to classes 将代码写入拦截器而不是类

. (referring (指

LinkedList 链表

instance with 实例

List 名单

interface) 接口)

Always try to refer your classes with interceptors which is a good practice 总是尝试用拦截器来引用你的课程,这是一个很好的做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM