java Linked List包装类

时间:2016-02-16 23:04:06

标签: java

我正在编写一个方法,假设查找并返回Linked-List中元素的值,显式定义为保存布尔值(包装类)。

这是代码:

 public boolean lookup(int index) {
  LLNode<Boolean> nodeptr = getFirst();
  for(int i = 0; i < index; i ++){
    if(nodeptr == null)
      return false; // ??????
    nodeptr = nodeptr.getNext();
  }
  return nodeptr.getElement();
}

我遇到的问题是,当我尝试在指定索引处返回元素时(如果它通过了我退出for循环的条件),它告诉我:

   incompatible types: Boolean cannot be converted to boolean

我认为这很奇怪,因为我假设Java 7应该自动解包我的包装类,所以我尝试了:

 public boolean lookup(int index) {
      LLNode<Boolean> nodeptr = getFirst();
      for(int i = 0; i < index; i ++){
        if(nodeptr == null)
          return false; // ??????
        nodeptr = nodeptr.getNext();
      }
      boolean b = nodeptr.getElement().booleanValue();
      return b;
    }

然后我得到了错误:

 Error: cannot find symbol
 symbol:   method booleanValue()
 location: class java.lang.Object

我不明白,因为我明确地查找并从API及其在lang包中复制/粘贴此方法,因此它应该自动导入。我手动导入此软件包时仍然遇到相同的错误。

有什么建议吗?

我被要求发布LLNode类:

public class LLNode<T> {

  private LLNode<T> next;

  private LLNode<T> last;

  private T element;

  public LLNode(T element, LLNode<T> next, LLNode<T> last) {
    this.element = element;
    this.next = next;
    this.last = last;
  }

  private void  setElement(T element) {
    this.element = element;
  }
  public T getElement() {
    return element;
  }

  public LLNode<T> getNext(){
    return next;
  }

  public LLNode<T> getLast() {
    return last;
  }

  public void setNext(LLNode<T> next) {
    this.next = next;
  }

   public void setLast(LLNode<T> last) {
    this.last = last;
  }


}

getFirst()方法:

protected LLNode<Boolean> getFirst() {
   return first;
 }

1 个答案:

答案 0 :(得分:0)

将查找方法更改为:

public boolean lookup(int index) {
  LLNode<Boolean> nodeptr = getFirst();
  for(int i = 0; i < index; i ++){
    if(nodeptr == null)
      return false; // ??????
    nodeptr = nodeptr.getNext();
  }
  Object element = nodeptr.getElement();
  if( element != null && element instanceof Boolean )
  {

     return ((Boolean)element).booleanValue();
  }

   return false;
}