If LinkedList is empty, don't return anything from the method that returns int?
EDIT: Solved. The return of 0 works, apparently!
Ok so short story, I have to return an int value, but nothing when the Linked List is empty. How to do it?
public int countDuplicates() {
int duplicates = 0;
ListNode current = front;
int num = current.data;
current = current.next;
while(current != null) {
if(current.data == num) {
duplicates++;
} else {
num = current.data;
}
current = current.next;
}
return duplicates;
}
When I try this:
if(front == null) {
return ;
}
This does not work. What can I do?
To keep the code as it is now, you must either return an int, throw an exception, or exit.
Return int: you need to specify a specific int value as the "fail" value and make sure that this never happens when that value is hit during "normal" execution.
Throw an exception: detailed in another answer - you've already run it.
Exit the program ... if it makes sense to do so.
The best option might be to change the code - for example, the function returns Integer, so null
there is an option . Of course, there are other ways to get around it.
You can throw IllegalArgumentException
: -
if(front == null) {
throw new IllegalArgumentException("List is empty");
}
If your method returns int
, you must define an acceptable value to represent "nothing". For example, 0
or if valid results >= 0
, use a negative value, for example -1
, to indicate "nothing."
Alternatively, change your method to return an object Integer
, in which case you can return null
.
You can either define a fixed value, for example Integer.MIN_VALUE
, which indicates the list is empty, or change your method declaration to public Integer countDuplicates()
and return null
when the list is empty.
If you don't want (or cannot) throw an exception, return some "exceptional value" such as a negative number. For example, there are many methods in Java indexOf(Object somethingToLookFor)
that return -1 if the element is not found.
In your example, -1 works like an exceptional one, because there can never be -1 duplicates.
Personally, I just returned 0 for an empty list. An empty list contains 0 duplicates. But if the spec insists on something exceptional, return -1. In the meantime, there is no need to know about it. ”
you can change the return value from int to an object like this
public Object countDuplicates() {
if(////condition)
return ///int;
else
return null;
You can return a negative value, or change the return type to string and parse the result to int.
public boolean isEmpty(){
if (head == null) return true;
else return false ;
}