[java] List(Collection)

한지개·2023년 1월 17일

java

목록 보기
2/9

List란?

  • 인덱스 순서로 저장
  • 중복된 데이터 저장 가능
  • 데이터를 저장하면 인덱스가 자동 부여되고 부여된 인덱스를 통해 데이터의 검색, 삭제가 가능
  • 초기 크기 지정하지 않아도 됨
  • 크기 조절 가능(가변적)

List 종류

ArrayList
List<E> 객체명 = new ArrayList<E>()

Vector
List<E> 객체명 = new Vector<E>()

Array
List<E> 객체명 = new LinkedList<E>()

셋 다 초기 저장 용량 생략 가능
제네릭 타입 생략시 Object타입

List 주요 메서드

삽입 관련

리턴 타입메서드내용
booleanadd(E e)List의 맨 뒤에 e삽입
voidadd(int index, E element)index 위치에 e삽입
booleanaddAll(Collection<? extends E> c)컬렉션 c의 모든 요소를 추가
Eset(int index, E element)해당 인덱스의 데이터 대체

사용 예시

프로그래머스 lv.0 짝수는 싫어요
boolean add(E e)

	public int[] solution(int n) {
        List<Integer> answer = new ArrayList<Integer>();

        for(int i=1; i<=n; i++){
          if(i%2 != 0) {
              answer.add(i);
          } 
        }

        return answer;
    }

(추가 예정)


리턴 관련

리턴 타입메서드내용
Eget(int index)인덱스의 요소 리턴
EelementAt(int index)인덱스의 요소 리턴
intsize()List가 포함하는 요소의 개수 리턴
booleanisEmpty()List가 비어있으면 true 리턴
booleancontains(Object o)List가 지정된 객체를 포함하고 있으면 true 리턴
intindexOf(Object o)o와 같은 첫 번째 요소의 인덱스 리턴, 없으면 -1 리턴
Object[]toArray()List의 모든 요소를 포함하는 배열 리턴

사용 예시

프로그래머스 lv.0 n의 배수 구하기
E get(int idex), int size()

	public int[] solution(int n, int[] numlist) {
        ArrayList<Integer> List = new ArrayList<>();
        for(int i = 0;i < numlist.length; i++){
            if(numlist[i] % n == 0) List.add(numlist[i]);
        }
            
        int[] answer = new int[List.size()];
            
        for(int i = 0; i< List.size(); i++){
            answer[i] = List.get(i);
        }
        
        return answer;
    }

(추가 ㅇㅖ정)


삭제 관련

리턴 타입메서드내용
Eremove(int index)인덱스의 요소 삭제
booleanremove(Object o)o와 같은 첫 번째 요소를 List에서 삭제
voidclear()List의 모든 요소 삭제

사용 예시
(추가 예정...)

profile
평생 소원이 누룽지

0개의 댓글