Return different type of data from a method in java?

前端 未结 13 1506
别那么骄傲
别那么骄傲 2020-12-05 02:18
public static void main(String args[]) {
    myMethod(); // i am calling static method from main()
 }

.

public static ? myMethod(){         


        
13条回答
  •  悲&欢浪女
    2020-12-05 03:00

    the approach you took is good. Just Implementation may need to be better. For instance ReturningValues should be well defined and Its better if you can make ReturningValues as 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;
         }
    
    } 
    

    Or if you have lots of key value pairs you can use HashMap then

    public static Map myMethod() {
      Map map = new HashMap();
      map.put(VALUE, "value");
      map.put(INDEX, 12);
      return Collections.unmodifiableMap(map); // try to use this 
    }
    

提交回复
热议问题