我正在编写一个方法,它应该查找并返回链表中元素的值,显式定义为保存布尔值(包装器类)。
代码如下:
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;
}
发布于 2016-02-17 07:17:24
将查找方法更改为:
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;
}
https://stackoverflow.com/questions/35444738
复制相似问题