logo

Java에서 배열을 반환하는 방법은 무엇입니까?

Java의 배열은 C/C++의 배열과 비교할 때 유사점이 많지만 구현 및 사용법이 다릅니다. 여기서는 Java에서 배열을 반환하는 방법에 대해 설명합니다.

Java에서 배열을 반환하려면 다음 사항을 주의해야 합니다.

핵심포인트 1: 배열을 반환하는 메서드의 반환 유형은 반환되는 배열의 데이터 유형과 동일한 데이터 유형의 배열이어야 합니다. 반환 유형은 일반적인 Integer, Double, Character, String 또는 사용자 정의 클래스 개체일 수 있습니다.



// Method returning an integer array. int[] methodName() {...}>
// Method returning a String array. String[] methodName() {...}>
// Method returning an array of objects of class named Students. Students[] methodName() {...}>

핵심포인트 2: 접근 한정자는 메소드의 사용법과 반환되는 배열을 고려하여 정확하게 사용해야 합니다. 정적 및 비정적 선언도 고려해야 합니다.

// Using public access modifier and static to call the method from a static class, method or block. public static char[] methodName() {...}>

핵심포인트 3: 반환되는 배열을 처리하려면 메서드 호출 시 동일한 데이터 유형 또는 이와 유사한 변수 배열이 있어야 합니다. 예를 들어, 모든 메서드에서 반환된 정수 배열은 다음과 같이 저장할 수 있습니다.

int[] storage = methodReturningArray();>

구현:

이를 더 잘 이해하기 위해 배열을 반환할 수 있는 몇 가지 다른 종류의 시나리오를 살펴볼 수 있습니다. 여기서는 시나리오에 대한 세 가지 예를 살펴보겠습니다.

  • 사례 1: 간단한 내장 배열
  • 사례 2: 객체 배열
  • 사례 3: 다차원 배열 반환

사례 1: Java에서 정수(내장 데이터 유형) 배열 반환

모든 내장 데이터 유형의 배열은 정수, 문자, 부동 소수점, 이중 등 모두 반환될 수 있으며 위에 나열된 사항을 염두에 두고 반환 문을 사용하기만 하면 됩니다.

자바




// Java Program to Illustrate Returning> // simple built-in arrays> // Importing input output classes> import> java.io.*;> // Main class> class> GFG {> >// Method 1> >// Main driver method> >public> static> void> main(String[] args)> >{> >// An integer array storing the returned array> >// from the method> >int>[] storage = methodReturningArray();> >// Printing the elements of the array> >for> (>int> i =>0>; i System.out.print(storage[i] + ' '); } // Method 2 // Returning an integer array public static int[] methodReturningArray() { int[] sample = { 1, 2, 3, 4 }; // Return statement of the method. return sample; } }>

취소선 마크다운

자바 유효한 식별자
>

>

산출

1 2 3 4>

사례 2: Java에서 객체 배열 반환

이는 내장 데이터 유형의 배열을 반환하는 경우와 정확히 유사한 방식으로 수행됩니다.

자바




// Java Program to Illustrate Returning> // an array of objects in java> // Importing all input output classes> import> java.io.*;> // Class 1> // Helper class> // Courses whose objects are returned as an array> class> Courses {> >String name;> >int> modules;> >// Constructor to instantiate class objects.> >public> Courses(String n,>int> m)> >{> >// This keyword refers to current instance itself> >this>.name = n;> >this>.modules = m;> >}> }> // Class 2> // Main class> class> GFG {> >// Method 1> >// Main driver method> >public> static> void> main(String[] args)> >{> >// Calling the method for returning an array of> >// objects of the Courses class.> >Courses[] sample = methodReturningArray();> >// Printing the returned array elements.> >for> (>int> i =>0>; i System.out.print(sample[i].name + ' - ' + sample[i].modules + ' modules '); } // Method 2 // Note that return type is an array public static Courses[] methodReturningArray() { // Declaring Array of objects of the Courses class Courses[] arr = new Courses[4]; // Custom array of objects arr[0] = new Courses('Java', 31); arr[1] = new Courses('C++', 26); arr[2] = new Courses('DSA', 24); arr[3] = new Courses('DBMS', 12); // Statement to return an array of objects return arr; } }>

>

>

산출

Java - 31 modules C++ - 26 modules DSA - 24 modules DBMS - 12 modules>

사례 3: 다차원 배열 반환

자바의 다차원 배열 배열 안의 배열의 배열이라고 할 수 있습니다. 가장 간단한 형태는 2차원 배열이 될 수 있습니다. 크기에 따라 크기와 선언이 있습니다. 여기에서는 1차원 배열과 매우 유사한 접근 방식을 사용하는 2차원 배열 반환이 아래에 설명되어 있습니다.

슬라이스 자바

자바




// Java Program to Illustrate Returning> // Multi-dimensional Arrays> // Importing input output classes> import> java.io.*;> // Main class> class> GFG {> >// Method 1> >// Main driver method> >public> static> void> main(String[] args)> >{> >// An integer 2D array storing the> >// returned array from the method> >int>[][] storage = methodReturningArray();> >// Printing the elements of the array> >// using nested for loops> >for> (>int> i =>0>; i for (int j = 0; j 0].length; j++) System.out.print(storage[i][j] + ' '); System.out.println(); } } // Method 2 // Returning an integer array public static int[][] methodReturningArray() { // Custom 2D integer array int[][] sample = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; // Return statement of the method return sample; } }>

>

>

산출

1 2 3 4 5 6 7 8 9>