简体   繁体   中英

Convert error in self-made generic List class

This code got an convert error that I'm not sure why is occur.

The error is:

List.java:131: error: incompatible types: Comparable cannot be converted to T
      this.insertAtFront(remove.firstNode.data);

And it came in every part of the code that use .data in List for ListNode.

I marked the lines that do the error.

Any ideas?

public class List<T extends Comparable<T>> {

private ListNode firstNode;
private ListNode lastNode;
private String name;

public List(String listName){
    name=listName;
    firstNode=lastNode=null;
}

public T removeAt(int k) throws ListIndexOutOfBound {
    List remove = new List();
    T o;
    if(k < 0 || k > checkSize()) throw new ListIndexOutOfBound();
    for(int i = 0; i < k; i++){
        try {
            remove.insertAtFront(firstNode.data);
            this.removeFromFront();
        } catch (Exception e) {
            while(!remove.isEmpty()){
                this.insertAtFront(**remove.firstNode.data**);
                remove.removeFromFront();
            }
            throw new ListIndexOutOfBound();
        }
    }
    **o = firstNode.data;**
    this.removeFromFront();
    while(!remove.isEmpty()){
        this.insertAtFront(**remove.firstNode.data**);
        remove.removeFromFront();
    }
    return o;
}
}

That's the ListNode class:

public class ListNode<T extends Comparable<T>> {

T data;
ListNode nextNode;

public ListNode(T o){
    this(o,null);
}

public ListNode(T o, ListNode node){
    data = o;
    nextNode = node;
}

public T getObject(){
    return data;
}
}

When you look at your List class, you will find that the definitions for both firstNode and lastNode do not contain a generic type information!

So change that to

ListNode<T> firstNode 

and that problem should go away. And the same when creating the "remove" list.

Omitted the generic information creates so called raw types. You get a warning each time you do that. Don't ignore that warning - simply fix all places where you used raw types!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM