好的,这是我正在使用的界面。
/* instance of classes that realize this interface can be compared */
public interface Comparable<E>
{
/* Method to compare this object to the argument object
* @param obj - the argument object
* @return - returns a negative integer if this object < obj
*/
int compareTo(E obj);
}
然后是有序列表类。
import java.util.*;
/* a class to represent an ordered List. the data is stored
* in a linked list data field
*/
public class OrderedList<E extends Comparable<E>>
implements Iterable<E>
{
/* a linked list to contain data */
private LinkedList<E> theList = new LinkedList<E>();
/* Insert Obj into the list preserving the lists order
* @param pre - the items in the list ordered
* @param post - obj has been inserted into the list such
* that the items are still in order
*/
public void add(E obj)
{
ListIterator<E> iter = theList.listIterator();
// find the insertion position and insert
while(iter.hasNext())
{
if(obj.compareTo(iter.next()) < 0)
{
// Iterator has stepped over the first element that
// is greater than the element to be inserted
// move the iterator back one
iter.previous();
// insert the element
iter.add(obj);
//exit the loop and return
return;
}
}
/* assert - all items were examined and no item is larger than
* the element to be inserted
* add the new item to the end of the list
*/
iter.add(obj);
}
/* returns the element at the specified position */
public E get(int index)
{
return theList.get(index);
}
/* returns an iterator to this ordered List */
public Iterator<E> iterator()
{
return theList.iterator();
}
/* returns the size of the list */
public int size()
{
return theList.size();
}
}
以及问题所在的测试类。
import java.util.*;
public class TestOrderedList
{
/* Traverses ordered list and displays each element
* displays and error message if an element is out of order
* @param testList - an ordered list of integers
*/
public static void traverseAndShow(OrderedList<Integer> testList)
{
int prevItem = testList.get(0);
/* traverse ordered list and display any value that
* is out of order
*/
for(int thisItem : testList)
{
System.out.println(thisItem);
if(prevItem > thisItem)
System.out.println("***Failed, value is " + thisItem);
prevItem = thisItem;
}
}
public static void main(String[] args)
{
OrderedList<Integer> testList = new OrderedList<Integer>();
final int MAX_INT = 500;
final int START_SIZE = 100;
// create a random generator
Random random = new Random();
for(int i = 0; i < START_SIZE; i++)
{
int anInteger = random.nextInt(MAX_INT);
testList.add(anInteger);
}
//Add to beginning and end of list.
testList.add(-1);
testList.add(MAX_INT + 1);
traverseAndShow(testList); // traverse and display
}
}
当我尝试在测试类中使用 Integer 时,出现“绑定(bind)不匹配”错误。问题出在哪里?
最佳答案
您已经定义了自己的 Comparable
接口(interface),而 Integer
并未实现该接口(interface)。从构建路径中删除自定义接口(interface),以便内置 java.lang.Comparable
可以用它代替
关于Java 绑定(bind)不匹配错误 - LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22612662/