1

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.

4

1 回答 1

2

你真的不需要做太多——它实际上是正确的。只需取出显式强制转换并compareTo在适当位置使用>

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--;
    }
}
于 2011-08-29T22:47:27.523 回答