Home > Java > javaTutorial > Example explanation of Collection in JavaSE

Example explanation of Collection in JavaSE

零下一度
Release: 2017-07-19 16:48:09
Original
1576 people have browsed it

                                                                                                                                                        StrINGBuilDER的播放的length can be changed. of. If you ask a little more in-depth and ask why there is such a difference, you will be dumbfounded and can only look at the interviewer with a cute look on his face.

Therefore, I want to systematically summarize the learning content in the form of writing an article, such as what the Collection architecture is like, what are the related inheritance and interface implementations, so that we can understand when to Which class to use and how to cooperate between classes will help you know how to solve the problem.

This series of articles is suitable for Java technical job candidates, computer major students in colleges and universities, and beginners learning Java in training institutions.

1.1 Understanding the Collection architecture

We have all used it The ArrayList class collects objects. For example, the add() method adds new objects and the remove() method removes objects. These are all familiar. But where did these methods come from? The following figure is the inheritance architecture diagram of this class:

##The ArrayList class is so complicated. If you want to show the entire Collection structure on one picture, it will probably be as tangled as a spider web. Simplifying it and ignoring some less important interfaces and implementation classes, we can get the following architecture diagram.

# #As can be seen from the picture, Collection is an interface that implements another interface Iterable. There are three interfaces under Collection that directly implement it, namely List, Set and Queue. There are two implementation classes under List, namely ArrayList and LinkedList; the commonly used implementation classes of Set are TreeSet and HashSet; under Queue there is Deque interface implementation, and then there is the implementation class ArrayDeque.

This picture will be the core of this series of articles, and will be mentioned repeatedly later. It might as well be called the Collection architecture diagram, and each article will introduce a part of it. Being familiar with this picture not only helps with understanding and learning, but also helps with memory. As for the detailed and comprehensive inheritance relationship and implementation architecture, which classes implement which interfaces and which classes they inherit, you can query them in the API documentation.

#1.2 List with index

List is implemented Collection interface, so we can say that List is a kind of Collection, its function is to collect objects, and its characteristic is to record the order of collected objects in the form of index. The common implementation class in List is ArrayList in the architecture diagram just mentioned. Readers who have forgotten it can turn to the front and take a look.

 1 /** 2  * ArrayList的实验用例 3  */ 4  5 import java.util.*; 6  7 public class Student { 8     public static void main(String[] args) { 9         List list = new ArrayList(); //使用JavaSE的List和ArrayList10         Scanner scanner = new Scanner(System.in);11         String name;12         while(true) {13             System.out.print("学生签到:");14             name = scanner.nextLine();15             if(name.equals("quit")) {16                 break;17             }18             list.add(name); //实用Add()方法收集对象19         }20         System.out.println("今天上来上课的学生名单:");21         foreach(list);22     }23 24     private static void foreach(List list) {25         for(int i = 0; i < list.size(); i++) {26             String student = (String) list.get(i); //使用get()方法依据索引取得收集的对象27             System.out.println(student);28         }29     }30 }
Copy after login

以上是ArrayList类的一个简单使用例子,模拟的是学生上课签到的情景。强烈建议读者跟我一样自己试着写一个简单用例,尤其是之前很少使用ArrayList的初学者,单纯的看和读跟实际敲代码产生的效果完全不一样。也可以照着我给出的例子敲,偷懒一点的话可以直接复制在机器上跑一遍。

从Collection架构图中可知,LinkedList同样也实现了List接口。就算只是把上面那个实验中的ArrayList全部改为LinkedList,程序照样可以运作,而且效果看起来完全相同。那么问题来了,我们什么时候应该使用ArrayList,什么时候又应该使用LinkedList呢?

1.2.1 ArrayList的特性

卡车和轮船都可以运送货物,我们可以根据不同的情况选择不同的运输方式。如果时间紧、运输量小,而且两个地点都在陆地上(例如北京到南京),那么我们可以使用汽车;如果时间多、运输量大,出发地和目的之间隔着海洋(例如大连到纽约),那么用船运是更好的选择。

刚毕业那会要找工作,为了面试背过“ArrayList像数组,读取速度快,但是需要调整索引的话表现很差;LinkedList像链表,调整索引的表现非常好,但是随机读取的速度比较慢”。那么我们可以问深一句,为什么会这样呢?不妨从源代码中找寻答案。

1     public boolean add(E e) {2         ensureCapacityInternal(size + 1);  // Increments modCount!!3         elementData[size++] = e;4         return true;5     }
Copy after login

上面这一段是JavaSE的源代码,我们可以看到ArrayList中的add()方法非常简单,跟我们平时使用数组一样。查看源代码中更多内容你会发现,ArrayList内部就是使用Object数组来保存所收集的对象,这就是为什么说“ArrayList就像数组”的原因。在考虑是否使用ArrayList的时候,我们可以相当于考虑是否要使用数组的特性。

1.2.2 LinkedList的特性

在学习Collection架构的时候,我们不妨可以多看源代码,看的时候优先比较几个基本方法的实现,例如add()、remove()等。从这些方法的实现,我们就可以看到不同实现类的特性。

    public boolean add(E e) {
        linkLast(e);return true;
    }/** * Links e as last element.     */void linkLast(E e) {final Node<E> l = last;final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;if (l == null)
            first = newNode;elsel.next = newNode;
        size++;
        modCount++;
    }
Copy after login

看到LinkdedList.add()的源代码,我们会发现其实现方式跟链表的实现如出一辙。如果last结点为null,那么说明链表为空,所以新添加的结点为头结点。如果last结点不等于null,那么把新添加的结点设为last的下一个结点,作为新的尾结点。

根据链表的特性,我们可以很快总结两点点特性:1.想要指定索引随机存取时,链接方式都得使用从第一个元素开始查找下一个元素的方式,效率比较糟糕;2.链接的每个元素都会参考下一个元素,这有利于调整索引顺序。

1.2.3 List总结

作为Collection三大阵营之一的List,最大的特点就是索引,我们可以通过索引做到随机存取。

List中常用的实现有ArrayList和LinkedList,各自的特性可以分别参考数组和链表。在比较它们之间区别的过程中,我们看了源代码,提倡在比较同一接口不同实现类时重点查看它们共同需要实现的方法,例如Collection中规定的add(),remove()等。 

面试中常见的List实现类其实还有Vector,其特性与ArrayList相同。不同在于Vector具有线程安全的特性,性能开销比较大,具体的内容会放在以后关于多线程的文章里。

The above is the detailed content of Example explanation of Collection in JavaSE. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template