본문 바로가기
카테고리 없음

[JAVA] ArrayList <-> Array

by 잉ㅈI 2024. 2. 20.

알고리즘 문제를 풀다가 ArrayList로 풀어야 하다가도 리턴은 Array여서 바꿔야할 경우가 많았구, 

특히 ArrayList는 Integer 이고, Array는 int 인 경우가 많아 이부분에 대해서 공부가 필요했다!

1. ArrayList 두가지 방법

1)

ArrayList<String> list = new ArrayList<>(Arrays.asList("aa","bb","cc"));

 

2)

ArrayList<String> list = new ArrayList<>();
list.add("bb");
list.add("aa");
list.add("cc");

 

+) ArrayList 출력은 그냥 값을 넣으면 된다! 참고로 그냥 배열(Array)은  Arrays.toString(list)로해야한다는 사실!

 

 

2.ArrayList<String> -> String[] 으로 바꾸는 방법

String[] array = list.toArray(new String[0]);

이때는 stream()을 할 필요는 없다!

  •  toArray()
    • 배열의 타입을 지정하는데 사용
    • 인자로 전달된 배열에 요소를 복사하고 반환
    • 반환 Object[]

결과로 반환될 배열의 타임을 String으로 지정하고 싶다면 -> new String[0]을 넣어주기!

** 배열의 크기 0으로 지정한 이유 : 결과로 반환될 배열의 크기를 예상할수 없음 + 필요한 크기에 맞게 자동 조정!

 

3.String[] -> ArrayList<String>

// String 배열 생성
String[] stringArray = {"apple", "banana", "cherry"};
        
// 배열을 List로 변환
List<String> stringList = Arrays.asList(stringArray);
        
// List를 ArrayList로 변환
ArrayList<String> arrayList = new ArrayList<>(stringList);
  • 먼저 List로 변환하기 
    • Arrays.asList(String배열);
  • 이후 List를 ArraList<String>으로 변환하기
    • new ArrayList<>(List);

한방에 변화시키기!!

ArrayList<String> arrayList = new ArrayList<>(Arrays.asList(stringArray));

4.ArrayList<Integer> -> int[]

ArrayList는 Integer로 하는 경우가 많은데, 바로 toArray()를 쓸수 없다!!

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(3,4,2));
int[] array = list.stream().mapToInt(Integer::intValue).toArray();
  • .stream()
    • stream()선언
  • .mapToInt(Integer::intValue)
    • Integer -> int 로 변하면서 맵돌리기
  • .toArray() 
    • int[] 배열로 반환하도록