Return different type of data from a method in java?

前端 未结 13 1490
别那么骄傲
别那么骄傲 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:14

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

    Then you can call then function as so

    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 doesn't force you to declare the type of ArrayList you are returning in the function declaration, so you can return an ArrayList of any type.

提交回复
热议问题