Java Generics, Inconvertible type, typecasting, heap d-ary
This is my remove method for d-ary heaps. I'm getting a lot of 'inconvertible type' error when i compile. Also note that my program extends Comparable.
public class HeapImpl12<T extends Comparable<? super T>> implements Heap12<T>
I know my array is not type开发者_运维问答 object but type T.
T[] _nodeArray = (T[]) new Comparable[DEFAULT_ARRAYSIZE];
Question: I understand everything should be type T, but when I was writing my code I got a lot of errors of "CAN'T CONVERT TYPE T TO TYPE INT", so i decided to typecast to make it same type (T) or (Integer). I realize now that doing this was wrong since I get "inconvertible type" error. Someone who has a high understanding on Java Generics please tell me techniques and tips to keep everything of type T.
public void remove(T o) {
for(int i = 0; i < _nodeArray.length; i++){
if(_nodeArray[i].equals(o)){
_nodeArray[i] = _nodeArray[_numNodes - 1];
if((Integer)_nodeArray[i] > parentIdx(i)){
bubbleUp((Integer)_nodeArray[i]);
}
else{
trickleDown((Integer)_nodeArray[i]);
}
}
else{
throw new NoSuchElementException();
}
_numNodes--;
}
}
errors: happen when i typecast (Integer). I can post all of my code if you want me to but i think this is enough.
You really don't have to do much -- it's practically right as it is. Just take out the explicit casts and use compareTo
in place on >
:
public void remove(T o) {
for(int i = 0; i < _nodeArray.length; i++){
if(_nodeArray[i].equals(o)){
_nodeArray[i] = _nodeArray[_numNodes - 1];
if(_nodeArray[i].compareTo(parentIdx(i)) > 0){
bubbleUp(_nodeArray[i]);
}
else{
trickleDown(_nodeArray[i]);
}
}
else{
throw new NoSuchElementException();
}
_numNodes--;
}
}
精彩评论