[java] Java 메소드에서 2 개의 값을 반환하는 방법은 무엇입니까?

Java 메소드에서 2 개의 값을 반환하려고하지만 이러한 오류가 발생합니다. 내 코드는 다음과 같습니다.

// Method code
public static int something(){
    int number1 = 1;
    int number2 = 2;

    return number1, number2;
}

// Main method code
public static void main(String[] args) {
    something();
    System.out.println(number1 + number2);
}

오류:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement
    at assignment.Main.something(Main.java:86)
    at assignment.Main.main(Main.java:53)

자바 결과 : 1



답변

두 값을 포함하는 배열을 반환하거나 일반 Pair클래스를 사용하는 대신 반환 하려는 결과를 나타내는 클래스를 만들고 해당 클래스의 인스턴스를 반환하십시오. 반원들에게 의미있는 이름을 준다. 배열을 사용하는 것보다이 방법의 이점은 형식 안전성이며 프로그램을 훨씬 쉽게 이해할 수있게합니다.

참고 : Pair여기에있는 다른 답변 중 일부에서 제안한 일반 클래스는 유형 안전성을 제공하지만 결과가 나타내는 것을 전달하지는 않습니다.

예 (실제로 의미있는 이름을 사용하지 않음) :

final class MyResult {
    private final int first;
    private final int second;

    public MyResult(int first, int second) {
        this.first = first;
        this.second = second;
    }

    public int getFirst() {
        return first;
    }

    public int getSecond() {
        return second;
    }
}

// ...

public static MyResult something() {
    int number1 = 1;
    int number2 = 2;

    return new MyResult(number1, number2);
}

public static void main(String[] args) {
    MyResult result = something();
    System.out.println(result.getFirst() + result.getSecond());
}


답변

Java는 다중 값 리턴을 지원하지 않습니다. 값의 배열을 반환합니다.

// Function code
public static int[] something(){
    int number1 = 1;
    int number2 = 2;
    return new int[] {number1, number2};
}

// Main class code
public static void main(String[] args) {
  int result[] = something();
  System.out.println(result[0] + result[1]);
}


답변

Pair두 값만 반환해야한다면 제네릭을 구현할 수 있습니다.

public class Pair<U, V> {

 /**
     * The first element of this <code>Pair</code>
     */
    private U first;

    /**
     * The second element of this <code>Pair</code>
     */
    private V second;

    /**
     * Constructs a new <code>Pair</code> with the given values.
     *
     * @param first  the first element
     * @param second the second element
     */
    public Pair(U first, V second) {

        this.first = first;
        this.second = second;
    }

//getter for first and second

그런 다음 메소드가 다음을 리턴하도록하십시오 Pair.

public Pair<Object, Object> getSomePair();


답변

Java에서는 하나의 값만 반환 할 수 있으므로 가장 간단한 방법은 다음과 같습니다.

return new Pair<Integer>(number1, number2);

업데이트 된 코드 버전은 다음과 같습니다.

public class Scratch
{
    // Function code
    public static Pair<Integer> something() {
        int number1 = 1;
        int number2 = 2;
        return new Pair<Integer>(number1, number2);
    }

    // Main class code
    public static void main(String[] args) {
        Pair<Integer> pair = something();
        System.out.println(pair.first() + pair.second());
    }
}

class Pair<T> {
    private final T m_first;
    private final T m_second;

    public Pair(T first, T second) {
        m_first = first;
        m_second = second;
    }

    public T first() {
        return m_first;
    }

    public T second() {
        return m_second;
    }
}


답변

SimpleEntry를 사용한 매우 간단하고 간단한 솔루션은 다음과 같습니다.

AbstractMap.Entry<String, Float> myTwoCents=new AbstractMap.SimpleEntry<>("maximum possible performance reached" , 99.9f);

String question=myTwoCents.getKey();
Float answer=myTwoCents.getValue();

Java 내장 함수 만 사용하며 safty 유형 이점이 있습니다.


답변

하나 이상의 반환 값을 반환하려면 컬렉션을 사용해야합니다

귀하의 경우 코드를 다음과 같이 작성하십시오

public static List something(){
        List<Integer> list = new ArrayList<Integer>();
        int number1 = 1;
        int number2 = 2;
        list.add(number1);
        list.add(number2);
        return list;
    }

    // Main class code
    public static void main(String[] args) {
      something();
      List<Integer> numList = something();
    }


답변

public class Mulretun
{
    public String name;;
    public String location;
    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]="siva";
        ar[1]="dallas";
        return ar; //returning two values at once
    }
    public static void main(String[] args)
    {
        Mulretun m=new Mulretun();
        String ar[] =m.getExample();
        int i;
        for(i=0;i<ar.length;i++)
        System.out.println("return values are: " + ar[i]);

    }
}

o/p:
return values are: siva
return values are: dallas