Array로 Queue 만들기

하온푸·2022년 9월 22일
0
int[] buffer = new int[bufferSize];
Integer[] boxedBuff = Arrays.stream(buffer).boxed().toArray(Integer[]::new);
Queue<Integer> queue = new LinkedList<>(Arrays.asList(boxedBuff));

bufferSize 라는 크기를 가진 array로 문제 편의상 모든 요소가 0인 크기가 bufferSize 인 Queue 를 만들고 싶다

int[] buffer = new int[bufferSize];

buffer 라는 크기가 bufferSize인 int형 array를 만들고

Integer[] boxedBuff = Arrays.stream(buffer).boxed().toArray(Integer[]::new);

Arrays.stream()을 사용해 buffer를 stream으로 바꾼 다음
boxed()로 int형을 Integer로 변환하고
toArray()의 argument로 "원하는 타입::new" 하면 됨
여기선 Integer[]로 바꿔야 하는 경우

Queue<Integer> queue = new LinkedList<>(Arrays.asList(boxedBuff));

이제 Integer 타입의 요소를 갖는 Queue를 생성해준다
Queue생성은 LinkedList를 이용하는게 국룰

LinkedList는 특성상 각 데이터를 node 객체에 담고 노드끼리 연결하기 때문에 배열처럼 요소 개수에 따라 늘려주거나 줄여줄 필요도 없고 수정할 때는 링크 끊고 이어주면 되기 때문에 편하다

profile
떵대지

0개의 댓글

Powered by GraphCDN, the GraphQL CDN