I've got stuck here in a simply method because I can't get it compiling.
I'm doing for each loop of objList which is an ArrayList<anObject>. I know the compiler can't get it compiled because there is no "Top-Level Return".
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return node;
}
}
}
Also I don't know what to return when the conditions doesn't met. I can't return a anObject because there isn't. Hope you can help me to provide solutions.
There are several things you can do:
nullNot the best practice, though, because the method's client will be forced to handle the possibly returned null (and if he doesn't, a NullPointerException can be thrown).
Your method would look like:
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return obj;
}
}
return null;
}
In this case, the client will have to deal with the case of null results:
anObject result = getObjByID(someId);
if (result != null) {
//proceed
}
IllegalArgumentException (or some other Exception)You can throw IllegalArgumentException to denote there's no corresponding Node for the provided id. The client will be forced to handle the exception.
Your method would look like:
anObject getObjByID(int id) throws IllegalArgumentException {
for(anObject obj : objList ){
if (obj.getID() == id){
return obj;
}
}
throw new IllegalArgumentException("Invalid index");
}
and the client will be have to handle the exception:
try {
anObject result = getObjByID(someId);
//proceed
} catch (IllegalArgumentException e) {
//handle the exception
}
Optional<T> typeJava8 introduces the Optonal<T> class, which is something like an alien - it may or it may not exist. Specifying the return type of a method to be Optional<T> helps the client have the awareness that a return value may exist, or may not.
Your method would look like:
Optional<anObject> getObjByID(int id){
Optional<anObject> result = Optional.empty();
for(anObject obj : objList ){
if (obj.getID() == id){
result = Optional.of(obj);
}
}
return result;
}
The client will use this method like this:
Optional<anObject> result = getObjByID(someId);
if (result.isPresent()) {
anObject realResultObject = result.get();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With