JAVA

JAVA ArrayList

체제 2021. 1. 11. 20:19

<ArrayList>

한번 생성되면 크기가 변하지 않는 일반적인 배열과 달리, 크기가 가변적으로 변화하는 선형리스트

* 저장용량이 초과되더라도, 부족한 크기 만큼 자동적으로 저장용량이 늘어난다 *

 

-ArrayList 선언

ArrayList list=new ArrayList() // 타입을 정하지 않고 선언 , 추천하진 않는 방법 

[타입명시]

ArrayList<String> list = new ArrayList<String>() ; // String 객체들만 연산 가능

ArryList<Integer> list = new ArrayList<Integer>() ; // Integer 객체들만 연산 가능 

 

-ArrayList에 값 추가 

=> add () 메소드 사용

1) add (index, value) 사용 ->  index 값 뒤에 value 삽입, 해당 인덱스부터 마지막까지 뒤로 1씩 밀려남 

2) add(value) 사용 -> 리스트의 맨 뒤에 데이터가 추가 

--------------------------------------------------------

ex) 

ArrayList<Integer> list = new ArraylList<Integer>() ;

list.add (3) ; // 값 3 추가

list.add(2,10) ; // index 2 다음에 10 삽입

--------------------------------------------------------

 

-ArrayList의 값 삭제

= > remove(index) 메소드 또는 clear() 메소드 사용

remove(index) ; // index 위치의 값 삭제하고 바로 뒤의 인덱스부터는 앞으로 1씩 당겨짐

clear() ; // 모든 값 제거 

--------------------------------------------------------

ex) 

ArrayList<Integer> list = new ArraylList<Integer>() ;

list.remove(1) ; // index 1 제거 

list.clear() ; // 모든 값 제거 

--------------------------------------------------------

 

-ArrayList의 값 출력

= > get(index) 메소드 사용 

--------------------------------------------------------

ex) 

ArrayList<Integer> list = new ArraylList<Integer>() ;

System.out.println(list.get(0)); // 0번째 index 출력

--------------------------------------------------------

* list의 모든 값을 출력하고 싶을 때*

-> for문 활용

 for( Integer i  : list ) {

System.out.println(i) ; // list 의 모든값 출력

}

 

-ArrayList의 값 검색

= > contains(value) 메소드 사용  : value 값의 존재 여부 확인 

-> 메소드 사용해서 value값이 존재한다면 true 리턴 

그렇지 않다면 false 리턴

 

=> indexof(value) : value 값이 있는 index 의 위치

-> value 값이 있으면 해당 값의 index 위치 반환 

없으면 -1 반환