从java中的方法返回不同类型的数据?

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()将返回String和int值。 所以从main()获取这些返回值我想出了以下解决方案。

创建一个类调用ReturningValues

 public class ReturningValues { private String value; private int index; // getters and setters here } 

并按如下方式更改myMethod()

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

现在我的问题是,有没有更简单的方法来实现这一点?

不可以.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; } } 

这样做的优点是可以传递ReturningValues ,例如线程之间,而不用担心意外地使事情不同步。

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

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

unit testing:

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

通常,如果您不确定最终返回的值是什么,则应考虑使用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 } 

这可以是解决方案之一。 但是你目前的解决方案还不错。 您还可以添加新变量并保持清洁,这不能用现有代码完成。

 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; } 

你采取的方法是好的。 只是实施可能需要更好。 例如,应该很好地定义ReturningValues,如果你可以将ReturningValues作为不可变的话,它会更好。

 // 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 myMethod() { Map map = new HashMap(); map.put(VALUE, "value"); map.put(INDEX, 12); return Collections.unmodifiableMap(map); // try to use this } 

你可以将回报作为一个对象。 你可以在你的“飞行中”创建该对象

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

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

最后我认为我的方式更好,因为当返回类型的数量更高时,这种实现以最佳方式执行。

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

您正在寻找的课程已经存在。 Map.Entry

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

然后:

 Entry valueAndIndex = myMethod(); int index = valueAndIndex.getKey(); String value = valueAndIndex.getValue(); 

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

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

在您调用方法的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,但对我来说,它完美无缺。

@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 } } 

我希望它很有用.. 🙂

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

  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! } }