Usage and the difference between ArrayList and LinkedList class

List is an ordered, repeatable set, each collection element has its corresponding sequence index. List allows repeated collection element, the collection can be accessed by the element at the specified index. List default settings set by the order of addition of the element index of the element, a first index element added to the List set to 0, the second 1, and so on.

List implement Collection interface, which has two main common implementation class: ArrayList and LinkedList class category.

ArrayList class

ArrayList class implements an array of variable size, including a data storage element is called. It also provides a quick way to access elements based on the index, to add and remove the tail of the members of the support is good. Use ArrayList collection was created to allow for the collection of elements fast random access, however, to insert and delete elements of the ArrayList relatively slow.

ArrayList common class constructor overloads two forms follows:

	ArrayList():构造一个初始容量为 10 的空列表。
	
	ArrayList(Collection<?extends E>c):构造一个包含指定 Collection 元素的列表,这些元素是按照该 Collection 的迭代器返回它们的顺序排列的。

ArrayList class contains all the methods other than the Collection interface, the method further comprising the following table List interface provided in FIG.

Method name Explanation
E get(int index) Get the specified index of this element set, E is the type of data elements in a set
int index(Object o) Returns the index of the specified collection element first appears. If this set contains the element, or -1
int lastIndexOf(Object o) Returns the index of the specified element in the last occurrence of this set, if this set contains the element, or -1
E set(int index, Eelement) Index location specified in this collection of elements to modify parameters specified for the target element. This method returns the specified index in this collection of original elements
List subList(int fromlndex, int tolndex) It returns a new collection, new collection contains all the elements between fromlndex and tolndex index. Contains elements fromlndex at, it does not contain the element at index tolndex

note: When you call List of set (int index, Object element) method to change the List collection element at the specified index, the index specified must be a valid index List collection. 4 is set, for example, the length can not be specified at the replacement index element 4, i.e. this approach does not change the length of a set of List.

Use an ArrayList class to add to the collection in three product information, including product number, name and price, then the output of these goods through the collection of information.

1. Create a commodity Product, and defines three attributes toString () method in the class, setter / getter methods were achieved. Implementation code as follows:

public class Product {
    // 商品类
    private int id; // 商品编号
    private String name; // 名称
    private float price; // 价格

    public Product(int id, String name, float price) {
        this.name = name;
        this.id = id;
        this.price = price;
    }

    // 这里是上面3个属性的setter/getter方法,这里省略
    public String toString() {
        return "商品编号:" + id + ",名称:" + name + ",价格:" + price;
    }
}

2. Create a test class, calling the constructor of the Product class instantiated three objects, and save the objects to the Product ArrayList collection. The last walk through the collection, output product information. To achieve the following:

public class Test {
    public static void main(String[] args) {
        Product pd1 = new Product(4, "木糖醇", 10);
        Product pd2 = new Product(5, "洗发水", 12);
        Product pd3 = new Product(3, "热水壶", 49);
        List list = new ArrayList(); // 创建集合
        list.add(pd1);
        list.add(pd2);
        list.add(pd3);
        System.out.println("*************** 商品信息 ***************");
        for (int i = 0; i < list.size(); i++) {
            // 循环遍历集合,输出集合元素
            Product product = (Product) list.get(i);
            System.out.println(product);
        }
    }
}

ArrayList set in this example is stored in the custom class Product object, the object class String stored is the same. Set the difference is that the presence get () method set List, may be obtained by the method corresponding to the index value, the acquired value of the Object class, it is necessary to convert the value Product class, so as to obtain product information.

Run result of the procedure shown below.

*************** 商品信息 ***************
商品编号:4,名称:木糖醇,价格:10.0
商品编号:5,名称:洗发水,价格:12.0
商品编号:3,名称:热水壶,价格:49.0

Note that distinguish the indexOf () method and lastIndexOf () method using List collection. The former is to obtain the minimum index location specified object, which object is to obtain the specified maximum index position . Provided that the specified object have a duplicate of the object List collection, these two otherwise identical method to get the index value.

() And the difference between the exemplary methods indexOf lastIndexOf () method.

public static void main(String[] args) {
    List list = new ArrayList();
    list.add("One");
    list.add("|");
    list.add("Two");
    list.add("|");
    list.add("Three");
    list.add("|");
    list.add("Four");
    System.out.println("list 集合中的元素数量:" + list.size());
    System.out.println("list 集合中的元素如下:");
    Iterator it = list.iterator();
    while (it.hasNext()) {
        System.out.print(it.next() + "、");
    }
    System.out.println("\n在 list 集合中'丨'第一次出现的位置是:" + list.indexOf("|"));
    System.out.println("在 list 集合中'丨'最后一次出现的位置是:" + list.lastIndexOf("|"));
}

The code to create a List collection list, and then add seven elements, because the index starts at 0, so the last index of the element 6. Output:

list 集合中的元素数量:7
list 集合中的元素如下:
One、|、Two、|、Three、|、Four、
在 list 集合中'|'第一次出现的位置是:1
在 list 集合中'|'最后一次出现的位置是:5

Must be used with the subList () method of the collection section taken List elements, new elements of the set contains the start position of the index, but the index does not contain the end position of the element. For example, subList (1,4) is the index method actually taken 1 to 3 of index elements, and form a new set of List.

DETAILED the subList Usage () method.

public static void main(String[] args) {
    List list = new ArrayList();
    list.add("One");
    list.add("Two");
    list.add("Three");
    list.add("Four");
    list.add("Five");
    list.add("Six");
    list.add("Seven");
    System.out.println("list 集合中的元素数量:" + list.size());
    System.out.println("list 集合中的元素如下:");
    Iterator it = list.iterator();
    while (it.hasNext()) {
        System.out.print(it.next() + "、");
    }
    List sublist = new ArrayList();
    sublist = list.subList(2, 5); // 从list集合中截取索引2~5的元素,保存到sublist集合中
    System.out.println("\nsublist 集合中元素数量:" + sublist.size());
    System.out.println("sublist 集合中的元素如下:");
    it = sublist.iterator();
    while (it.hasNext()) {
        System.out.print(it.next() + "、");
    }
}

Output:

list 集合中的元素数量:7
list 集合中的元素如下:
One、Two、Three、Four、Five、Six、Seven、
sublist 集合中元素数量:3
sublist 集合中的元素如下:
Three、Four、Five、

LinkedList class

LinkedList class objects stored linked list structure, the advantage of this structure is easy to insert or delete elements to the collection. When the collection to frequently insert and delete elements using analog high LinkedList ArrayList class effect, but the speed random access LinkedList class element is relatively slow. Random access retrieval element here refers to a particular set of index position.

In addition to containing LinkedList class Collection List interface and all interface methods, but also provides in particular a method shown in the following table.

Method name Explanation
void addFirst(E e) Adds the specified element to this at the beginning of the collection
void addLast(E e) Adds the specified element to the end of the collection
E getFirst() It returns the first element of this collection
E getLast() Returns the last element of this collection
E removeFirst() Removes the first element in this collection
E removeLast() Removes the last element in this collection

In the warehouse management system to record trade names warehousing and ship the merchandise first name and last entry - a trade name. Finishing the set of functions used LinkedList, as follows:

public class Test {
    public static void main(String[] args) {
        LinkedList<String> products = new LinkedList<String>(); // 创建集合对象
        String p1 = new String("六角螺母");
        String p2 = new String("10A 电缆线");
        String p3 = new String("5M 卷尺");
        String p4 = new String("4CM 原木方板");
        products.add(p1); // 将 p1 对象添加到 LinkedList 集合中
        products.add(p2); // 将 p2 对象添加到 LinkedList 集合中
        products.add(p3); // 将 p3 对象添加到 LinkedList 集合中
        products.add(p4); // 将 p4 对象添加到 LinkedList 集合中
        String p5 = new String("标准文件夹小柜");
        products.addLast(p5); // 向集合的末尾添加p5对象
        System.out.print("*************** 商品信息 ***************");
        System.out.println("\n目前商品有:");
        for (int i = 0; i < products.size(); i++) {
            System.out.print(products.get(i) + "\t");
        }
        System.out.println("\n第一个商品的名称为:" + products.getFirst());
        System.out.println("最后一个商品的名称为:" + products.getLast());
        products.removeLast(); // 删除最后一个元素
        System.out.println("删除最后的元素,目前商品有:");
        for (int i = 0; i < products.size(); i++) {
            System.out.print(products.get(i) + "\t");
        }
    }
}

As the above code, first create a String object 5, respectively, p1, p2, p3, p4 and p5. While p1, p2, p3, and p4 object using add () method LinkedList added to the collection, use addLast () method to add objects to p5 LinkedList collection. Are calling getFirst LinkedList class () method and getLast () method to get the first and last name merchandise. Finally, use removeLast () method to delete the last product information, and print out the remaining product information.

LinkedList is generics in Java, the type of data specified collection of elements, such as elements of type String specified here, is not the addition of non-collection of elements of type String.

Run the program execution results are as follows:

*************** 商品信息 ***************
目前商品有:
六角螺母    10A 电缆线    5M 卷尺    4CM 原木方板    标准文件夹小柜   
第一个商品的名称为:六角螺母
最后一个商品的名称为:标准文件夹小柜
删除最后的元素,目前商品有:
六角螺母    10A 电缆线    5M 卷尺    4CM 原木方板

ArrayList class differences and class LinkedList

ArrayList and LinkedList are the List interface implementation class, so they have achieved all of the methods unrealized List, the only way to achieve different.

ArrayList dynamic array data structure is based on access speed than the elements LinkedList. LinkedList is a linked list data structure to achieve based on memory space occupied by relatively large, but better than the ArrayList when the bulk insert or delete data.

Demand for quick access to objects, would be better using ArrayList achieve the efficiency. Require frequent insert and delete elements when using high-ArrayList LinkedList class effect analogy to the collection.

Different structures correspond to different algorithms, consider saving some space, some consider increasing operational efficiency, for programmers, they are like a "bear's paw" and "fish" can not have both. High operating speed is often at the expense of space for the price, while saving space is often at the expense of speed for the price.

Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104714586