Home » Java » java – I am trying to return a class datatype using Hashmap get() but gives me error saying "must return value of type". Please advise-Exceptionshub

java – I am trying to return a class datatype using Hashmap get() but gives me error saying "must return value of type". Please advise-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

My return value for method getVal complains with the error:

must return value of type test1.

I am not sure why would it complain about return type as I assume get would give you the value for the corresponding key. Please help me understand this logic.

public class test1 {
    //There is some class named test1
    public test1() { //Default Constructor
    }

    public test1 getVal(String name) {
        return sample.get(name);
    }
}

public class test {
    public test() {
        HashMap<String, test1> sample = new Hashmap<>();
        sample.put("Name", new test1());
    }
}
How to&Answers:

Your HashMap named sample is not visible in getVal method. You can add it as parameter to that method or make the HashMap sample visible to the getVal method.

Answer:

The issue is your use of test1 in the type signature of the function here:

public test1 getVal(String name) {
       ^

You intend this function to return a String type, not a test1 type. Try:

public String getVal(String name) {
       ^