• Tags , ,
  •         
  • www.breakyizhan.com
  •    

    在Java中返回多个值

    Java不支持多值返回。但是我们可以使用以下解决方案来返回多个值。

    如果所有返回的元素都是相同类型的

    我们可以用Java返回一个数组。下面是一个展示相同的Java程序。

    // A Java program to demonstrate that a method
    // can return multiple values of same type by
    // returning an array
    class Test
    {
        // Returns an array such that first element
        // of array is a+b, and second element is a-b
        static int[] getSumAndSub(int a, int b)
        {
            int[] ans = new int[2];
            ans[0] = a + b;
            ans[1] = a - b;
    
            // returning array of elements
            return ans;
        }
    
        // Driver method
        public static void main(String[] args)
        {
            int[] ans = getSumAndSub(100,50);
            System.out.println("Sum = " + ans[0]);
            System.out.println("Sub = " + ans[1]);
        }
    }
    

    上述代码的输出将是:

    Sum = 150
    Sub = 50

     

    如果返回的元素是不同类型的

    我们可以将所有返回的类型封装到一个类中,然后返回该类的一个对象。让我们看看下面的代码。

    // A Java program to demonstrate that we can return
    // multiple values of different types by making a class
    // and returning an object of class.
    
    // A class that is used to store and return
    // two members of different types
    class MultiDiv
    {
        int mul;    // To store multiplication
        double div; // To store division
        MultiDiv(int m, double d)
        {
            mul = m;
            div = d;
        }
    }
    
    class Test
    {
        static MultiDiv getMultandDiv(int a, int b)
        {
            // Returning multiple values of different
            // types by returning an object
            return new MultiDiv(a*b, (double)a/b);
        }
    
        // Driver code
        public static void main(String[] args)
        {
            MultiDiv ans = getMultandDiv(10, 20);
            System.out.println("Multiplication = " + ans.mul);
            System.out.println("Division = " + ans.div);
        }
    }
    

    输出:

     Multiplication = 200
    Division = 0.5

     
    转载请保留页面地址:https://www.breakyizhan.com/java/4112.html