W3schools - List
찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요
ArrayList
Is a resizable array
Elements can be added and removed from an ArrayList whenever you want
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
// Elements in an ArrayList are actually object.
// To use primitive type, you must specify an equivalent wrapper class
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Create an ArrayList object
myNumbers.clear(); // to remove all
myNumbers.add(33); // add item, (item)
myNumbers.add(12);
myNumbers.add(12);
myNumbers.get(1); // to access an element, (index)
myNumbers.set(1, 22); // to change item, (index, item)
myNumbers.remove(2); // to remove item, (index)
myNumbers.size(); // to find out how many elements have
Collections.sort(myNumbers); // Sort myNumbers
for (int i : myNumbers) { // Loop through
System.out.print(i + “ ”);
} // output will be 22 23
}
}
LinkedList vs ArrayList
LinkedList is almost identical to the ArrayList
How the ArrayList works
-
ArrayList class has a regular array inside it
-
When an element is added, it is placed into the array
-
If the array is not big enough, a new, larger array is created to replace the old one
-
And old one is removed
How the LinkedList works
-
LinkedList stores its items in containers.
-
The list has a link to the first container and each container has a link to the next container in the list
-
To add an element to the list, the element is placed into a new container
When to use
-
ArrayList for storing and accessing data
-
LinkedList to manipulate data
Methods
addFirst() : Adds an item to the beginning of the list
addLast() : Add an item to the end of the list
removeFirst() : Remove an item from the beginning of the list
removeLast() : Remove and item from the end of the list
getFirst() : Get the item at the beginning of the list
getLast() : Get the item at the end of the list