如何在 Java 中的静态 int 方法中返回多个数组



如何添加多个数组返回?
我想返回数组a和数组output
我在方法中添加了 int [] [],但我不知道如何添加返回

public class Bubble 
{
    public static int[][] bubbles( int[]a)
    {
        int output[]= new int [2 ];
        Random g = new Random();
        a = new int [4];
        for (int i = 0 ; i<a.length ; i++)
        { a[i] = g.nextInt(4)+1;}
        int count1=0;
        for (int i = 0 ; i<a.length ; i++)
        { a[i] = g.nextInt(4)+1;}
        int swap = 0;
        for ( int pass = 0; pass < a.length ; pass++ )
        { 
            for ( int i = 0; i < a.length - 1; i++ )
            {
                count1 ++;
                if ( a[ i ] > a[ i + 1 ] ) 
                {
                    int temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                    swap++;
                    output[0]=swap;
                    output[1]=count1;
                }
            }   
        }
        return (output);
    }   
}

可能的最佳解决方案是此处提供的解决方案。

将方法签名更改为

 public static Object[] bubbles(int[] a)

并返回您的结果,例如

 return new Object[]{a, output};

如果要使用方法的返回值,可以这样做。

 // somewhere in your code
 Object[] res = bubbles(yourArray); 
 int[] a = (int[]) res [0];
 int[] output = (int[]) res[1];

您已经意识到,为了返回两个数组,您需要返回一个包含这两个数组的对象,并且您已经通过使返回类型int[][] 来做好准备。 现在,代替return (output),您可以执行以下操作:

int[][] result = new int[2][];
result[0] = a;
result[1] = output;
return result;

return new int[][]{a, output};

这样称呼它:

int[] arr = new int[]{1,2,3};  
int[][] bubResult = bubbles(arr);
System.out.println("Array of random numbers that was "a" in bubbles:");
System.out.println(Arrays.toString(bubResult[0]);
System.out.println("Two-element array that was "output" in bubbles:");
System.out.println(Arrays.toString(bubResult[1]);

简短的回答是,您不需要同时返回两者。你已经有a.
int[] a是可变的,因此将通过bubbles方法进行更改。只需有气泡返回输出:

public static int[] bubbles( int[]a)

并从气泡中删除a的初始化:

// a = new int [4];  

并按如下方式使用bubbles

public static void main(String[] args) {
    int[] a = new int [4];
    int[] output = bubbles(a);
    System.out.println(Arrays.toString(a));  
    System.out.println(Arrays.toString(output));
}


-----------------------------------------------------------------但是,如果您确实需要从 bubbles 返回两个int[]对象,您可以通过多种方式执行此操作,例如使用 List

更改bubbles的签名以返回列表:

public static List<int[]> bubbles()

并使用 in bubbles 创建a对象:

int[] a = new int [4];

并添加所需的代码以返回List

    List<int[]> returnValue = new ArrayList<>();
    returnValue.add(a);
    returnValue.add(output);
    return returnValue;

通过以下方式使用它:

public static void main(String[] args) {
    List<int[]> returnValue = bubbles();
    System.out.println(Arrays.toString(returnValue.get(0))); //prints a
    System.out.println(Arrays.toString(returnValue.get(1))); //prints output
}

最新更新