logo

Jak zwrócić tablicę w Javie

W tej sekcji dowiemy się, jak zwrócić tablicę w Javie.

Pamiętać:

  • Metoda może zwrócić referencję do tablicy.
  • Typ zwracany przez metodę musi być zadeklarowany jako tablica prawidłowego typu danych.

Przykład 1

W poniższym przykładzie metoda zwraca tablicę typu całkowitego.

 import java.util.Arrays; public class ReturnArrayExample1 { public static void main(String args[]) { int[] a=numbers(); //obtain the array for (int i = 0; i <a.length; i++) for loop to print the array system.out.print( a[i]+ ' '); } public static int[] numbers() { arr="{5,6,7,8,9};" initializing return arr; < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-misc/62/how-return-an-array-java.webp" alt="How to return an array in Java"> <h3>Example 2</h3> <p>In the following example, the method returns an array of double type. </p> <pre> public class ReturnArrayExample3 { public static double[] returnArray( ) { double[] arr = new double [3]; // Creating an array of 3 elements arr[0]=6.9; arr [1]=2.5; arr [2]=11.5; return( x ); // Return the reference of the array } public static void main(String[] args) { double[] a; //variable to store returned array a = returnArray(); //called method for (int i = 0; i <a.length; i++) for loop to print the array system.out.println( a[i]+ ' '); } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-misc/62/how-return-an-array-java-2.webp" alt="How to return an array in Java"> <h3>Example 3</h3> <p>In the following example, method returns an array of object type.</p> <pre> import java.util.Arrays; class ReturnArrayExample3 { public static int[] returnArray() { int a1=20; int a2=23; int a3=87; return new int[] {a1,a2,a3}; //returns array } public static void main(String args[]) { int[] arr=returnArray(); //invoking method and storing returned array into arr System.out.println(Arrays.toString(arr)); //returns the string representation of the object } } </pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-misc/62/how-return-an-array-java-3.webp" alt="How to return an array in Java"> <hr></a.length;></pre></a.length;>

Wyjście:

Jak zwrócić tablicę w Javie