배열을 다루는데 유용한 메소드들이 정의되어 있다
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4};
// 복사
int[] arr2 = Arrays.copyOf(arr, arr.length);
int[] arr3 = Arrays.copyOf(arr, 4);
int[] arr4 = Arrays.copyOf(arr, 8);
int[] arr5 = Arrays.copyOfRange(arr, 2, 4);
int[] arr6 = Arrays.copyOfRange(arr, 0, 7);
System.out.println("arr2 = " + Arrays.toString(arr2));
System.out.println("arr3 = " + Arrays.toString(arr3));
System.out.println("arr4 = " + Arrays.toString(arr4));
System.out.println("arr5 = " + Arrays.toString(arr5));
System.out.println("arr6 = " + Arrays.toString(arr6));
}
[출력]
arr2 = [0, 1, 2, 3, 4]
arr3 = [0, 1, 2, 3]
arr4 = [0, 1, 2, 3, 4, 0, 0, 0]
arr5 = [2, 3]
arr6 = [0, 1, 2, 3, 4, 0, 0]
public static void main(String[] args) {
int[] arr7 = new int[5];
Arrays.fill(arr7, 9);
System.out.println("arr7 = " + Arrays.toString(arr7));
Arrays.setAll(arr7, i -> (int) (Math.random() * 6) + 1);
System.out.println("arr7 = " + Arrays.toString(arr7));
for (int i : arr7) {
char[] graph = new char[i];
Arrays.fill(graph, '*');
System.out.println(new String(graph) + i);
}
}
[출력]
arr7 = [9, 9, 9, 9, 9]
arr7 = [3, 1, 6, 6, 3]
***3
*1
******6
******6
***3
public static void main(String[] args) {
char[] chArr = {'A','D','C','B','E'};
System.out.println("chArr = " + Arrays.toString(chArr));
Arrays.sort(chArr);
System.out.println("chArr = " + Arrays.toString(chArr));
System.out.println("index of B = " + Arrays.binarySearch(chArr, 'B'));
}
[출력]
chArr = [A, D, C, B, E]
chArr = [A, B, C, D, E]
index of B = 1
public static void main(String[] args) {
String[][] str2D = new String[][]{{"aaa", "bbb"}, {"AAA", "BBB"}};
String[][] str2D2 = new String[][]{{"aaa", "bbb"}, {"AAA", "BBB"}};
System.out.println(Arrays.equals(str2D, str2D2));
System.out.println(Arrays.deepEquals(str2D, str2D2));
}
[출력]
false
true
1차원 배열은 equals(), 다차원 배열은 deepEquals()
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3, 4};
int[][] arr2D = {{11, 12, 13}, {21, 22, 23}};
// 출력
System.out.println("arr = " + Arrays.toString(arr));
System.out.println("arr2D.toString() = " + Arrays.deepToString(arr2D));
}
[출력]
arr = [0, 1, 2, 3, 4]
arr2D.toString() = [[11, 12, 13], [21, 22, 23]]
1차원 배열은 toString(), 다차원 배열은 deepToString()
List list = Arrays.asList(new Integer[]{1,2,3,4,5});
List list = Arrays.asList(1,2,3,4,5);
list.add(6); // UnsupportedOperationException 예외 발생
asList()로 변환한 List는 크기 변경이 불가하다. -> 추가/삭제 불가
오직 저장된 내용만 변경이 가능
크기를 변경할 수 있는 List가 필요하다면 추가적인 변환이 필요하다
List list = new ArrayList(Arrays.asList(1,2,3,4,5));