int peek() {
if(isEmpty()) {
System.out.println("Stack underflow peek can't be done");
return Integer.MIN_VALUE;
}
else {
return list.get(list.size()-1);
}
}
Is there any other way to return nothing?
CodePudding user response:
You generally have several ways to signal an error back to the caller:
- Return a dummy value that indicates an error, such as Integer.MIN_VALUE. Generally not favoured, will lead to problems if the dummy value naturally occurs in the data.
- Return a null value. Requires the return type to be changed to a reference type such as Integer. Also out of fashion as nulls have various well-documented issues.
- Change the return type to be one of the Optional types, such as OptionalInt, and return an empty value if an error occurs.
- Throw an exception.
Your code is using option #1, which is not generally recommended, but may make sense in very specific cases (e.g. min function over a list of integers). #4 is generally the preferred option, with #3 as an alternative if you want to avoid exceptions for any reason.
CodePudding user response:
This is commonly used as indicator to caller that queue/stack is empty. The problem is return type is primitive int , so you have to return some integer, you cannot return null.
I see this in many examples because programmer assumes here that Integer.MIN_VALUE will be never valid case and nobody will push that value onto queue/stack.
Ideally I would return Integer instead of int and return null if stack is empty. We could throw exception but I will avoid it since caller will need to handle exception for every peek or top or pop. Handling null is easier than this.