What is the correct way to use the generic type in this situation? Consider the following code:
public class GTree<T> {
private int level;
private T value;
private String key;
private LinkedList<GTree<T>> subTrees;
private GTree<T> parent;
public class NodeEntry<T extends Comparable<? super T>> implements Comparable<T>{
private T value;
private String key;
public NodeEntry(T v, String k) {
this.value = v;
this.key = k;
}
public T getValue() {
return value;
}
public String getKey() {
return key;
}
public int compareTo(T o) {
return getValue().compareTo(o);
}
public int compareTo(GTree<T>.NodeEntry<T> o) {
// TODO Auto-generated method stub
return value.compareTo(o.getValue());
}
}
private void getAllBranches(LinkedList<LinkedList<NodeEntry<T>>> path)
{
if(leaf())
{
LinkedList<NodeEntry<T>> lastPath = path.getLast();
NodeEntry<T> p = new NodeEntry<T>(value, key);
lastPath.addLast(p);
return;
}
else
{
LinkedList<NodeEntry<T>> lastPath = path.getLast();
NodeEntry<T> p = new NodeEntry<T>(value, key);
lastPath.addLast(p);
....
for(int i = 0; i < subTrees.size(); i++)
{
T x = subTrees.get(i).getValue();
if(subTrees.get(i).leaf())
{
lastPath.addLast(new NodeEntry<T>(subTrees.get(i).getValue(), subTrees.get(i).getKey()));
....
}
else
subTrees.get(i).getAllBranches(path);
}
}
}
}
The compiler is complaining about the generic type T whenever I use it, except when I define the variable x: Bound mismatch: The type T is not a valid substitute for the bounded parameter <T extends Comparable<? super T>> of the type GTree. NodeEntry
The issue is that NodeEntry specifically is looking for a class that is of type T
that extends Comparable
but the GTree class does not have this bound. To resolve this, you must either remove the bound requirement from NodeEntry to define the type parameter T from GTree with the upper bound T extends Comparable
.
If NodeEntry expects the same value as GTree then in this specific case GTree's type parameter T should be bound to Comparable.
public static class GTree<T extends Comparable<T>> {
private int level;
private T value;
private String key;
private LinkedList<GTree<T>> subTrees;
private GTree<T> parent;
public static class NodeEntry<T extends Comparable<T>> implements Comparable<T> {
private T value;
private String key;
public NodeEntry(T v, String k) {
this.value = v;
this.key = k;
}
public T getValue() {
return value;
}
public String getKey() {
return key;
}
@Override
public int compareTo(T o) {
return value.compareTo(o);
}
}
private void getAllBranches(LinkedList<LinkedList<NodeEntry<T>>> path) {
// more
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.