36
public static void main(String args[]) {
    myMethod(); // i am calling static method from main()
 }

.

public static ? myMethod(){ // ? = what should be the return type
    return value;// is String
    return index;// is int
}

myMethod() will return String and int value. So take these returning values from main() i came up with following solution.

create a class call ReturningValues

public class ReturningValues {
private String value;
private int index;

// getters and setters here
}

and change myMethod() as follows.

 public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues();
    rv.setValue("value");
    rv.setIndex(12);
    return rv;
}

Now my question,is there any easier way to achieve this??

4

14 回答 14

25

我使用枚举创建各种返回类型。它不会自动定义。该实现看起来像工厂模式。

public  enum  SmartReturn {

    IntegerType, DoubleType;

    @SuppressWarnings("unchecked")
    public <T> T comeback(String value) {
        switch (this) {
            case IntegerType:
                return (T) Integer.valueOf(value);
            case DoubleType:
                return (T) Double.valueOf(value);
            default:
                return null;
        }
    }
}

单元测试:

public class MultipleReturnTypeTest {

  @Test
  public void returnIntegerOrString() {
     Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer);
     Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double);
  }

}
于 2015-09-09T19:00:41.867 回答
18

不能。Java 方法只能返回一个结果(void、原语或对象),而创建这样的struct-type 类正是您的做法。

需要注意的是,通常可以像这样使您的类ReturningValues不可变:

public class ReturningValues {
    public final String value;
    public final int index;

    public ReturningValues(String value, int index) {
        this.value = value;
        this.index = index;
    }
}

这样做的好处是 aReturningValues可以在线程之间传递,而不必担心意外使事情不同步。

于 2013-08-09T06:12:11.170 回答
7

通常,如果您不确定最终会返回什么值,则应考虑使用 return-type 作为所有返回值的超类。在这种情况下,如果您需要返回 String 或 int,请考虑返回 Object 类(它是 java 中定义的所有类的基类)。

但要小心让instanceof 检查您调用此方法的位置。否则你最终可能会得到ClassCastException

public static void main(String args[]) {
        Object obj = myMethod(); // i am calling static method from main() which return Object
    if(obj instanceof String){
    // Do something
    }else(obj instance of Integer) {
    //do something else
     }
于 2013-08-09T06:13:19.627 回答
3

你采取的方法很好。只是实施可能需要更好。例如 ReturningValues 应该被很好地定义,如果你可以将 ReturningValues 设置为immutable会更好。

// this approach is better
public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues("value", 12);
    return rv;
}


public final class ReturningValues {
    private final String value;
    private final int index;


    public ReturningValues(String value, int index) {
      this.value = value;
      this.index = index;
     }

} 

或者,如果您有很多键值对,则可以使用 HashMap

public static Map<String,Object> myMethod() {
  Map<String,Object> map = new HashMap<String,Object>();
  map.put(VALUE, "value");
  map.put(INDEX, 12);
  return Collections.unmodifiableMap(map); // try to use this 
}
于 2013-08-09T06:20:08.057 回答
2

您要查找的课程已经存在。 Map.Entry

public static Entry<Integer,String> myMethod(){
    return new SimpleEntry<>(12, "value");
}

然后:

Entry<Integer,String> valueAndIndex = myMethod();
int index = valueAndIndex.getKey();
String value = valueAndIndex.getValue();

它只是一个存储键和值的简单的两字段数据结构。如果您需要进行任何特殊处理、存储两个以上的字段或有任何其他边缘情况,您应该创建自己的类,否则,Map.Entry它是未充分利用的 Java 类之一,非常适合此类情况。

于 2017-10-18T14:25:39.870 回答
1

这可以是解决方案之一。但是您目前的解决方案已经足够好了。您还可以添加新变量并保持其干净,这是当前代码无法完成的。

private static final int INDEX_OF_STRING_PARAM = 0;
private static final int INDEX_OF_INT_PARAM = 1;

public static Object[] myMethod() {
    Object[] values = new Object[2];
    values[INDEX_OF_STRING_PARAM] = "value";
    values[INDEX_OF_INT_PARAM] = 12;
    return values;
}
于 2013-08-09T06:12:51.657 回答
1

我知道这已经晚了,但我认为这对来寻找答案的人会有所帮助。您可以使用 aBundle返回多个数据类型值,而无需创建其他方法。我试过了,效果很好。

在调用方法的 MainActivity 中:

Bundle myBundle = method();
String myString = myBundle.getString("myS");
String myInt = myBundle.getInt("myI");

方法:

public Bundle method() {
    mBundle = new Bundle();
    String typicalString = "This is String";
    Int typicalInt = 1;
    mBundle.putString("myS", typicalString);
    mBundle.putInt("myI", typicalInt);
    return mBundle;
}

PS:我不确定实现这样的 Bundle 是否可以,但对我来说,效果很好。

于 2018-01-22T02:37:09.927 回答
1

我只想发表我的看法

所以你需要创建一个通用的返回类型,并通过不同类型的具体返回类型来实现。Service 类可以创建不同类型的对象具体类并作为泛型类型返回。

public interface GenericReturnType{
    public static RETURN_TYPE enum{
        MACHINE, PERSON;    
    }
    public RETURN_TYPE getReturnType();
}

public class PersonReturnType implements GenericReturnType{
    // CONSTRUCTORS //

    // GETTRE AND SETTER //

    public RETURN_TYPE getReturnType(){
        return PERSON;
    }
    public String getAddress(){
        return something;
    }
}

public class MachineReturnType implements GenericReturnType{
    // CONSTRUCTORS //

    // GETTRE AND SETTER //

    public RETURN_TYPE getReturnType(){
        return MACHINE;
    }
    public String getManufatureName(){
        return something;
    }
}


public class TestService{
    public GenericReturnType getObject(// some input //){
        GenericReturnType obj ;
        if(// some code //){
            obj = new  PersonReturnType();
            // some code //
        }
        if(// some code //){
            obj = new  MachineReturnType();
            // some code //
        }
        return obj;
    }
}

public class TestDriver{
    TestService service = new TestService();
    GenericReturnType genObj = TestService.getObject(// some input //);
    if(genObj.getReturnType() == RETURN_TYPE.MACHINE){
        // SOME CODE // 
    }
    if(genObj.getReturnType() == RETURN_TYPE.PERSON){
        // SOME CODE // 
    }
}
于 2019-01-15T09:32:12.353 回答
0

最后我认为我的方法更好,因为当返回类型的数量变高时,这种实现会以最好的方式做到这一点。

public static ReturningValues myMethod() {
ReturningValues rv = new ReturningValues();
rv.setValue("value");
rv.setIndex(12);
return rv;
}
于 2013-08-09T12:09:00.313 回答
0

@ruchira 你的解决方案它自己是最好的。但我认为如果它只是关于整数和字符串,我们可以以非常简单的方式做到这一点..

 class B {   
    public String myfun() {         
        int a=2;           //Integer .. you could use scanner or pass parameters ..i have simply assigned
        String b="hi";      //String
        return Integer.toString(a)+","+b; //returnig string and int with "," in middle          
    }       
}

class A {    
    public static void main(String args[]){

        B obj=new B();  // obj of class B with myfun() method  
        String returned[]=obj.myfun().split(",");
             //splitting integer and string values with "," and storing them in array   
        int b1=Integer.parseInt(returned[0]); //converting first value in array to integer.    
        System.out.println(returned[0]); //printing integer    
        System.out.println(returned[1]); //printing String
    }
}

我希望它有用.. :)

于 2013-08-09T06:57:31.013 回答
0

一种解决方案可以如下。函数可以定义如下(输入的数量/类型可以套利)

static List<Object> multiTypeInputOut (int a, double b, String c, List<Object> d)
{
    List<Object> multiTypes = new ArrayList<>();
    multiTypes.add(a);
    multiTypes.add(b);
    multiTypes.add(c);
    multiTypes.add(d);
    return multiTypes; 
}

调用此类方法/函数时,示例如下(只需记住并正确设置返回类型的顺序):

   List<Object> HelloWorldStrList = new ArrayList<Object>(Arrays.asList("Welcome", "Hello", "World"));
   List<Object>  multiType = multiTypeInputOut (1, 2.1, "HelloWorld",  HelloWorldStrList);
   int entry1 = (int) multiType.get(0);
   double entry2 = (double) multiType.get(1);
   String entry3 = (String) multiType.get(2);
   List<Object>  entry4 = (List<Object>) multiType.get(3);
于 2021-05-05T14:11:50.900 回答
0

public ArrayList divineCast(String object) {  
        try
        {
            Integer result = Integer.parseInt(object);
            ArrayList<Integer> generic = new   ArrayList<Integer>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a Integer
        }
        try
        {
            Float result = Float.parseFloat(object);
            ArrayList<Float> generic = new   ArrayList<Float>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a Float
        }
        try
        {
            Double result = Double.parseDouble(object);
            ArrayList<Double> generic = new   ArrayList<Double>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a double
        }
        try
        {
            Boolean result = Boolean.parseBoolean(object);
            ArrayList<Boolean> generic = new   ArrayList<Boolean>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a Boolean
        }
        try
        {
            String result = String.valueOf(object);
            ArrayList<String> generic = new   ArrayList<String>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a String
        }
        return null;

    }

然后你可以调用 then 函数

String test1 = "0.90854938";
String test2 = "true";
System.out.println(divineCast(test1).get(0));
System.out.println(divineCast(test1).get(0).getClass());
System.out.println(divineCast(test2).get(0));
System.out.println(divineCast(test2).get(0).getClass());

Java 不会强制您在函数声明中声明要返回的 ArrayList 的类型,因此您可以返回任何类型的 ArrayList。

于 2020-02-11T05:30:05.923 回答
0

您可以将返回作为对象。您在您的

function: if(int) 
 return new object(){
   int nr=..
}

字符串也一样。但我担心这是一个昂贵的解决方案......

于 2018-03-11T05:35:25.543 回答
-1

方法重载在这里可以派上用场,例如:

<code>
public class myClass 
{
    int add(int a, int b) 
    {
         return (a + b);
    }

    String add(String a, String b)
    {
         return (c + d);
    }

    public static void main(String args[]) 
    {
        myClass ob1 = new myClass);
        ob1.add(2, 3);
        //will return 5
        ob1.add("Hello, ", "World!");
        //will return Hello, World!
    }

}

于 2017-06-01T19:12:30.790 回答