LinkedList and ArrayList

What is a list

I used to use ArrayList for brain death, but it seems that there are actually various things.

LinkedArrayListTest.java


package listTest;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class LinkedArrayListTest {
	
	public static void main(String[] args) {
		measure(1000000);
	}
	
	private static void linked(int num) {
		List<String> list = new LinkedList<>();
		for (int i = 0; i < num; i++) {
			list.add("asd");
		}
	}
	
	private static void array(int num) {
		List<String> list = new ArrayList<>();
		for (int i = 0; i < num; i++) {
			list.add("asd");
		}
	}
	
	public static void measure(int num) {
		Long start = System.nanoTime();
		linked(num);
		Long middle = System.nanoTime();
		array(num);
		Long end = System.nanoTime();
		System.out.println("Linked : " + (middle - start) + " ns\r\nArray : " + (end - middle) + " ns");
	}
}

result

Linked : 19082700 ns
Array  : 14878000 ns

Well, I can not say anything because the number of times is small, but it seems that Linked List is faster if only add

However, it seems that Array is faster to bring in a specific element such as get (0).

If you just want to create a list and for loop, you can use LinkedList, and if you want to use a lot of order, it's like Array.

I would be happy if such minor performance problems could be considered if there was spare capacity.

Recommended Posts

LinkedList and ArrayList
Difference between ArrayList and LinkedList
ArrayList
java ArrayList, Vector, LinkedList comparison
Difference between List and ArrayList
[Java] Difference between array and ArrayList
About removeAll and retainAll of ArrayList
[Practice] ArrayList
== and equals
[Practice] ArrayList
ArrayList practice
Difference between EMPTY_ELEMENTDATA and DEFAULTCAPACITY_EMPTY_ELEMENTDATA in ArrayList
Sort ArrayList by dragging and dropping ItemTouchHelper
ArrayList class