공log/[P&B]

[P&B] #21 PreCodingTest

ming_OoO 2023. 8. 8. 16:22
728x90

프리코딩테스트 2-3

 

2)Teacher Mistake

오답 노트 코드

class Solution {
	public static int[] solution(int[] nums) {
        List<Integer> list1 = Arrays.stream(nums).boxed().toList();
        ArrayList<Integer> list2 = new ArrayList<>();

        for (int i = 1; i <= nums.length; i++) {
            if (!list1.contains(i)) {
                list2.add(i);
            }
        }

        int[] ans = list2.stream().mapToInt(Integer::intValue).toArray();

        return ans;
    }
}

 

문제 풀이 코멘트

 List는 인터페이스입니다. 즉, Java의 다형성에 의해서 만약 아래와 같이 list를 List 자료형으로 선언한 경우, 그 구현체를 ArrayList로도 구현할 수 있지만 LinkedList로 구현 할수도 있습니다.

 ArrayList는 클래스입니다. ArrayList 역시 아래처럼 List 인터페이스를 구현하고 있기 때문에 List가 제공하는 기능들을 다 제공할 수 있으므로 List 선언 시 구현 인스턴스의 자료형으로 작성할 수 있습니다.

  • Arrays.stream(nums).boxed().toList();
    • Arrays.stream(nums): 배열 nums를 스트림으로 변환합니다.
    • .boxed(): 기본 타입의 요소들을 박싱하여 래퍼(wrapper) 객체로 변환합니다. (예: int를 Integer로 변환)
    • .toList(): 스트림의 요소들을 리스트로 수집합니다.
  • list2.stream().mapToInt(Integer::intValue).toArray();
    • list2.stream(): 리스트 list2를 스트림으로 변환합니다.
    • .mapToInt(Integer::intValue): 스트림의 각 요소를 int 값으로 변환합니다. 이 때, Integer::intValue 메서드 레퍼런스를 사용하여 각 Integer 객체를 int로 변환합니다.
    • .toArray(): 스트림의 요소들을 int 배열로 수집합니다.

 

728x90