我的Java项目中有两个类:

public abstract class Heap<T extends Comparable<T>> {

      private Comparable<T> data[];
      private int numberOfElements;

      public Heap( int size ) {

           //I am also not sure if this cast will work or is best practice

           data = (Comparable<T>[]) new Comparable<?>[ size + 1 ];

           numberOfElements = 0;
      }

      public void incrementNumberOfElements() { numberOfElements++; }

      public int getNumberOfElements() { return numberOfElements; }

      public Comparable<T>[] getData() { return data; }

      public abstract void insert( Comparable<T> element );
}

class MinHeap<T extends Comparable<T>> extends Heap<T> {

     public MinHeap( int size ) { super(size); }

     public void insert( Comparable<T> element ) {

           incrementNumberOfElements();

           Comparable<T> data[] = getData();

           int current = getNumberOfElements();

           data[ current ] = element;


         //The error is with compareTo()
          while ( current / 2 >= 1 && data[ current ].compareTo( data[ current / 2 ] ) < 0 ) {

                      //code

          }
     }

 }


我用compareTo()方法收到以下编译时错误:The method compareTo(T) in the type Comparable<T> is not applicable for the arguments (Comparable<T>)。如果我将这样的数据强制转换为data[ current ].compareTo( (T) data[ current / 2 ] ),则错误消失了,但是有警告。

我的问题是:添加强制转换data[ current ].compareTo( (T) data[ current / 2 ] )是实现这项工作的最佳方法吗?如果没有,有什么建议可以使它更好?我的目标是创建一个可与实现Comparable接口的任何类一起使用的Heap。

我对使用泛型不太熟悉,因此欢迎您提供任何有用的建议。

最佳答案

public void insert( T element )-因为要插入类型T或更高的元素(class MinHeap<T extends Comparable<T>>),所以指定T必须扩展Comparable。
我已将您的代码更改为使用数组列表而不是数组,不确定是否需要使用数组。

import java.util.ArrayList;
import java.util.List;

public abstract class Heap<T extends Comparable<T>> {

private List<T> data;
private int numberOfElements;

public Heap( int size ) {

    //I am also not sure if this cast will work or is best practice

    data = new ArrayList<T>(size + 1 );

    numberOfElements = 0;
}

public void incrementNumberOfElements() { numberOfElements++; }
public int getNumberOfElements() { return numberOfElements; }
public List<T> getData() { return data; }
public abstract void insert( T element );
}

class MinHeap<T extends Comparable<T>> extends Heap<T> {

public MinHeap( int size ) { super(size); }
public void insert( T element ) {

    incrementNumberOfElements();
    List<T> data = getData();
    int current = getNumberOfElements();
    data.set(current, element);

    //The error is with compareTo()
    while ( current / 2 >= 1 && data.get(current).compareTo( data.get(current / 2) ) < 0 ) {

        //code

    }
}

}

关于java - 如何获得此Java泛型代码以使其正常工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23033128/

10-12 20:19