【问题标题】:Return different type of data from a method in java?从java中的方法返回不同类型的数据?
【发布时间】:2013-08-11 01:08:44
【问题描述】:
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;
}

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

【问题讨论】:

  • 您可以使用PropertiesHashMap 甚至List,但我认为您的ReturnValues 更合适,因为它对于该方法将返回什么是明确的
  • 索引和值有什么关系?

标签: java return return-type


【解决方案1】:

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

请注意,经常可以像这样使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 可以在线程之间传递,而不必担心意外地使事情不同步。

【讨论】:

【解决方案2】:

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

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

【讨论】:

  • 这行得通,但它的类型安全性要差得多,而且更难阅读。
  • @chrylis 是的,我完全同意。我已经提到,目前的代码只有两个或三个返回值是可管理的。但更好的是 OP 的版本,因为它类型安全且更易于理解。
【解决方案3】:

一般来说,如果你不确定最终会返回什么值,你应该考虑使用 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
     }

【讨论】:

    【解决方案4】:

    你采取的方法很好。 只是实施可能需要更好。 例如 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<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 
    }
    

    【讨论】:

    • 如果您的 indexvalue 字段是私有的,您需要添加 getter 才能访问它们。
    【解决方案5】:

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

    我希望它有用.. :)

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

        【解决方案7】:

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

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

        【讨论】:

        • 我个人认为像方法一样使用枚举看起来有点奇怪。更像是一个黑客。
        【解决方案8】:

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

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

        【讨论】:

          【解决方案9】:

          您要查找的课程已经存在。 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 类之一,非常适合此类情况.

          【讨论】:

            【解决方案10】:

            我知道这已经晚了,但我认为这对来寻找答案的人会有所帮助。您可以使用 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;
            }
            

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

            【讨论】:

              【解决方案11】:

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

              中“即时”创建该对象
              function: if(int) 
               return new object(){
                 int nr=..
              }
              

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

              【讨论】:

                【解决方案12】:

                我只是想说说我的看法

                所以你需要创建一个通用的返回类型,并通过不同类型的具体返回类型来实现。 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 // 
                    }
                }
                

                【讨论】:

                  【解决方案13】:
                  
                  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。

                  【讨论】:

                    【解决方案14】:

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

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

                    【讨论】:

                      猜你喜欢
                      • 2015-02-05
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2022-11-27
                      • 2021-12-01
                      • 2015-05-22
                      相关资源
                      最近更新 更多