Array Methods
Coddy Java 여정의 기초 섹션에 포함된 레슨 — 73개 중 61번째.
배열에는 많은 메서드(기능)가 포함되어 있습니다. 메서드에 접근하려면 다음과 같이 작성하세요:
Arrays.methodName(arrayName, otherParameters)다음은 기본 메서드 목록입니다:
fill(array, value)- 배열을 특정 값으로 채웁니다
toString()- 배열을 문자열로 변환합니다
sort(array)- 배열을 오름차순으로 정렬합니다
equals(array1, array2)- 두 배열을 비교하여 동일한지 확인합니다
다음은 fill 메서드를 toString과 함께 사용하는 방법의 예입니다:
int[] numbers = new int[5];
Arrays.fill(numbers, 10);
System.out.println(Arrays.toString(numbers));이것은 [10, 10, 10, 10, 10]을 출력합니다.
sort 메서드 예제:
int[] numbers = {5, 2, 9, 1, 5, 6};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));이것은 [1, 2, 5, 5, 6, 9]를 출력합니다.
챌린지
쉬움두 개의 배열을 인자로 받는 merge라는 이름의 메서드를 작성하세요. 이 메서드는 두 배열을 **하나의 정렬된** 배열로 병합하여 반환합니다.
중요: 최종 병합된 배열은 오름차순으로 정렬되어야 합니다.
예를 들어, 다음과 같은 인자가 주어지면: merge(new String[] {"1", "4", "2"}, new String[] {"2", "5", "9"}) 결과로 ["1", "2", "2", "4", "5", "9"]를 반환합니다 (결과가 정렬되어 있음에 유의하세요).
한 배열에서 다른 배열로 요소를 복사하려면 System.arraycopy()를 사용하세요. 구문은 다음과 같습니다:
System.arraycopy(sourceArray, sourceStartPosition, destinationArray, destinationStartPosition, length)예시:
// Source array
String[] sourceArray = {"1", "2", "3", "4", "5"};
// Destination array
String[] destinationArray = new String[5];
// Copy elements from sourceArray to destinationArray
System.arraycopy(sourceArray, 0, destinationArray, 0, 5);복사 후의 대상 배열(Destination array): 1 2 3 4 5
직접 해보기
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static String[] merge(String[] arr1, String[] arr2) {
// 여기에 코드를 작성하세요
return null;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String textArr1 = scanner.nextLine();
String textArr2 = scanner.nextLine();
String[] arr1 = textArr1.split(",");
String[] arr2 = textArr2.split(",");
String[] mergedArray = merge(arr1, arr2);
System.out.println(Arrays.toString(mergedArray));
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
기초의 모든 레슨
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 411Arrays Basics
Declaring ArraysAccessing ElementsModifying ArraysArray MethodsRecap - Product ArrayRecap - Reversed Array3Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else