How to write Java function that returns values of multiple data types?

后端 未结 11 1561
耶瑟儿~
耶瑟儿~ 2021-01-03 23:34

For example, I want to create a function that can return any number (negative, zero, or positive).

However, based on certain exceptions, I\'d like the function to re

11条回答
  •  孤街浪徒
    2021-01-04 00:04

    I would say it is possible. But not directly.

    I haven't gone through the program given in the question. I am answering this knowing this is an old post. Might help someone.

    Add your values to a Map like below. And get it with its key!

    public static HashMap returnAnyType(){
        String x = "This";
        int a = 9;
    
        HashMap myMap = new HashMap();
        myMap.put("stringVal", x);
        myMap.put("intVal", a);
        return myMap;
    }
    
    String theStringFromTheMap = (String) returnAnyType().get("stringVal");
    int theIntFromTheMap = (Integer) returnAnyType().get("intVal");
    
    System.out.println("String : " + theStringFromTheMap + " is great !");   
    System.out.println("Integer: " + Math.addExact(theIntFromTheMap, 10));
    

    Output (both are returned from same method):

    String : This is great!
    Integer: 19
    

    Note:
    This is not a good practice. But it helps sometimes when it is needed!

提交回复
热议问题