I am practicing recursion and using a recursive helper method. In my helper method, an error appears saying that
The method someMethod(K) in the type Tree is not applicable for the arguments (K, List, int).
However, I do not want to use the someMethod(K k)
method as I am trying to use the someMethod(K k, List<K> L, int n)
helper method. How do I make Eclipse "know" that I'm trying to use the other method?
Here's what I have thus far:
public List<K> someMethod(K k) {
List<K> L=new LinkedList<K>();
if (lookup(k) != null) {
return someMethod(k, L, 0);
}
return L;
}
private List<K> someMethod(K k, List<K> L, int n) {
if (this.k.compareTo(k) == 0) {
L.add(this.k);
return list;
}
if (this.k.compareTo(k) < 0) {
right.someMethod(k, L, n); //error here
L.add(this.k);
}
if (this.k.compareTo(k) > 0) {
left.someMethod(k, L, n); //error here
L.add(this.k);
}
}
Edit: declarations for left and right:
private Tree<K, V> left, right;
First problem I see in the second method is that you are only returning something in the case when the statement
if (this.k.compareTo(k) == 0)
is true.
The compiler should give you an error because your method is declared to return List<K>
private List<K> someMethod(K k, List<K> L, int n)
To solve this, you should return something either in each if
statement, or at the bottom of your method. Based on your logic, you want to return an error value when no matches satisfying the above if
statement are found. Thus, for example, you could return null
by putting this statement at the bottom of your method:
return null;
Or, if you don't want to deal with null
values, return an empty list:
return new ArrayList<K>();
If you make this change your code compiles fine on my machine.
Here is an Ideone example that compiles fine with the change I suggested.
Furthermore, as @ajb mentioned in the comments, you aren't really taking care of the base case for your recursion.
Meaning, you are not changing the arguments:
K k, List<K> L, int n
of your recursive method when you pass them through recursion and thus will end up in an "infinite" recursion causing StackOverFlowError
in the case where no elements satisfy the condition
if(this.k.compareTo(k) == 0) {
L.add(this.k);
return list; // this returns from recursion but nothing else
}
You should define some sort of a base case that will stop the recursion no matter if you find matches or not.