java中链表中的不兼容类型错误

时间:2013-10-09 06:03:33

标签: java linked-list

public static Node stringToList(String s) {
    Node<Character> head = new Node<Character>();
    for(int i = 0; i < s.length(); i++) {
    head = new Node<Character>(s.charAt(i), head);
    }
    char c = head.item;      // error line
}



I am trying to convert the char value in the nodes to an integer value and I believe I have found a way to do so. Just want to store the item in nodes to variable c for the time being. And then I got the error message. 
Why am I getting an incompatible types error? And it says "required: character".

// Node class:
public class Node<Item> {
    public Item item;           //as you can see, it a generic class
    public Node<Item> next;
    Node() { 
        item = null; 
        next = null;      
    } 
    Node(Item i) {
        item = i;
        next = null;
    }
    Node(Item i, Node<Item> p) {
        item = i;
        next = p;
    }
}

完整错误消息:文件:/Users/Michelle/BigInt.java [line:11]错误:/Users/Michelle/BigInt.java:11:找到不兼容的类型:java.lang.Object required:char

1 个答案:

答案 0 :(得分:0)

编辑: 根据您的新编辑(包括错误消息),这可能就是您正在做的事情

Integer oneBoxed = 1;
char d = (char) oneBoxed; //error... required: char, found: Integer 

你应该做的是

Integer oneBoxed = 1;
char d = (char) oneBoxed.intValue();

使用Generics时要小心,因为你被迫打包所有原语。

您是新来的,但请在提问时尝试发布更多信息; - )

---原始答案---

我相对肯定你正试图

  1. 将盒装角色投射到盒装整数中。 OR
  2. 将盒装整数投入盒装角色。
  3. 您要执行从Character到Integer的强制转换,您必须先将它们取消装箱。

    Integer one = 1;
    Character b = one;
        //Error will be
        //
        //required: Character
        //found: Integer
    

    相反的方式

    Character c = 'c';
    Integer cInt =  c;
        //Error will be
        //
        //required: Integer
        //found: Character
    

    要正确转换这些值,您需要先取消装入rValue。

    Integer one = 1;
    Character b = (char) one.intValue();
    //Yay! No Error
    

    Character c = 'c';
    Integer cInt = (int) c.charValue();
    //Yay! No Error Again!