콜렉션 프레임워크 - ArrayList
2019-09-07
ArrayList
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars);
}
}
ArrayList는 동적으로 크기가 조절되는 배열으로, 새 원소를 삽입하면 크기가 늘어난다.
배열(array)은 한 번 크기를 정하면 변경할 수 없기에 배열보다 편리하지만 데이터 추가 및 삭제 시 메모리를 재할당하기 때문에 속도가 배열보다 느리다.
ArrayList의 기본적인 메소드에 대해 알아보겠다.
- get(int index)
- Returns the element at the specified position in this list.
- size()
- Returns the number of elements in this list.
- isEmpty()
- Returns true if this list contains no elements.
- void clear()
- This method is used to remove all the elements from any list.
- Object clone()
- This method is used to return a shallow copy of an ArrayList. //얕은 복사
remove()
- remove(int index)
- Removes the element at the specified position in this list.
- remove(Object o)
- Removes the first occurrence of the specified element from this list, if it is present.
import java.util.*;
public class Test
{
public static void main(String[] args)
{
// Demonstrating remove on ArrayList
List<String> myAlist = new ArrayList<String>();
myAlist.add("Geeks");
myAlist.add("Practice");
myAlist.add("Quiz");
System.out.println("Original ArrayList : " + myAlist);
myAlist.remove("Quiz");
System.out.println("Modified ArrayList : " + myAlist);
}
}
Output:
Original ArrayList : [Geeks, Practice, Quiz]
Modified ArrayList : [Geeks, Practice]
add()
- boolean add(Object o)
- This method appends the specified element to the end of this list.
- void add(int index, Object element)
- This method inserts the specified element E at the specified position in this list. It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices).
삽입 실패시 Exception으로 IndexOutOfBoundsException을 던진다.
위치를 지정하지 않으면 끝에 추가되고, 지정을 하면 기존 위치에 있던 element들이 오른쪽으로 shift된다는 점을 주의하자.
import java.io.*;
import java.util.ArrayList;
public class Test {
public static void main(String[] args)
{
// create an empty array list with an initial capacity
ArrayList<Integer> arrlist = new ArrayList<Integer>(5);
// use add() method to add elements in the list
arrlist.add(10);
arrlist.add(22);
arrlist.add(30);
arrlist.add(40);
// adding element 35 at fourth position
arrlist.add(3, 35);
// let us print all the elements available in list
for (Integer number : arrlist) {
System.out.println("Number = " + number);
}
}
}
Output:
Number = 10
Number = 22
Number = 30
Number = 35
Number = 40
Iterator
ArrayList를 탐색할 때 Iterator 인터페이스를 쓴다.
public interface Iterator {
boolean hasNext();
Object next();
void remove();
}
boolean hasNext() 메소드는 읽어 올 요소가 남아있으면 true, 없으면 false를 반환한다.
Iterator it<Integer> = numbers.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
Object next() 메소드는 읽어 올 요소가 남아있으면 true, 없으면 false를 반환한다.
void remove() 메소드는 next()로 읽어 온 요소를 삭제한다.
while(it.hasNext()){
int value = it.next();
if(value == 30){
it.remove();
}
}
foreach()
import java.util.*;
public class Test {
public static void main(String[] args)
{
// create an ArrayList which going to
// contains a list of Numbers
ArrayList<Integer> Numbers = new ArrayList<Integer>();
// Add Number to list
Numbers.add(23);
Numbers.add(32);
Numbers.add(45);
Numbers.add(63);
// forEach method of ArrayList and
// print numbers
Numbers.forEach((n) -> System.out.println(n));
}
}
Output
23
32
45
63
for(int value : Numbers){
System.out.println(value);
}
사실 이게 제일 내 눈엔 편하게 보인다.