[java] 메서드가 둘 이상의 객체를 반환하도록하는 방법은 무엇입니까?
You could return an array...
public static String[] multipleReturnMethod(){
String a = "a";
String b = "b";
return new String[] { a, b };
}
Or a list, or a type which encapsulates the two values, etc...
You can only return a single value from a method, but that value may itself give access to multiple "subvalues".
If you can give more information about what you're trying to do, we may be able to help more.
-------------------Not possible without chaning the return object:
Either create a class for it:
class Strings { String a, b; Strings(String a, String b) { this.a = a; this.b = b; } } public static Strings multipleReturnMethod(){ return new Strings("a", "b"); }
Or return an array
public static String[] multipleReturnMethod(){ return new String[] { a, b }; }
If you want to keep the signature, you could concatenate the strings with a defined delimiter:
public static final String DELIMITER = "\t"; // or something else
// not used in strings
public static String multipleReturnMethod(){
String a = "a";
String b = "b";
return a + DELIMITER + b;
}
(although I prefer changeing the signature and returning an array or a collection of values, see Jon's answer)
-------------------If they are all the same type of object then the simplest way is to just return an array of that type of object
public static String[] methodA(){
String[] temp = new String[5];
// do work
return temp;
}
If you wish to return different types of objects then return an ArrayList of objects.
public static ArrayList<Object> methodB(){
ArrayList<Object> temp = new ArrayList<Object>();
// do work
return temp;
}
-------------------Java에서는 불가능합니다. 반환하려는 요소 주위에 래퍼 클래스를 만들고 해당 단일 요소를 반환하고 반환하려는 모든 항목을 포함해야합니다.
FunctionalJava에는 제품에 대한 편리한 클래스 P가있어이를 쉽게 수행 할 수 있습니다. http://functionaljava.googlecode.com/svn/artifacts/3.0/javadoc/fj/P.html
return P.p(a,b);
-------------------하나 이상의 객체를 반환하는 것은 불가능합니다. 해결책은 반환하려는 객체가 포함 된 객체를 반환하는 것입니다.
-------------------더 복잡한 예가있는 경우 리스너 패턴을 사용할 수 있습니다.
interface ResultListener {
void resultOne(String text);
void resultTwo(String text, int number);
}
public static void multipleReturnMethod(ResultListener result){
result.resultOne("a");
result.resultOne("b");
result.resultTwo("C", 1);
}
보시다시피 유형의 조합 또는 조합을 사용하여 모든 결과 조합을 호출자에게 반환 할 수 있습니다.
-------------------한 가지 방법은 출력 객체를 메소드에 전달하는 것입니다. 예를 들어 arraylist 형식으로 다음과 같습니다.
public static ArrayList<String> multipleReturnMethod(ArrayList<String> output) {
String a = "a";
String b = "b";
output.add(a);
output.add(b);
return output; //not really necessary
}
물론 출력은 메서드 외부에서 만들어야합니다.
출처
https://stackoverflow.com/questions/7415134