class MyVector
{
class Cell
{
//5 private Object data
private Cell next;
}
private static Cell _head;
public void add(Object data)
{
Cell p = new Cell();
//Cell p = new Cell();
if( _head == null)
p = _head;
else
p = getTail();
//20 p.data = data
}
//找到尾车厢
private Cell getTail()
{
Cell p = new Cell();
if(_head == null)
return _head;
p = _head;
while(p.next==null)
p = p.next;
return p;
}
public Object get(int n)
{
Cell p = new Cell();
p = _head;
for(int i = 0; i < n; i++)
{
p = p.next;
}
return p.data;
}
public int size()
{
return 0;
}
}
public class MyA
{
public static void main(String[] args)
{
MyVector v = new MyVector();
v.add("qqq");
v.add("aaa");
}
}
运行总会有错误:
Exception in thread "main" java.lang.NullPointerException
at Mypackage.MyVector$Cell.access$0(MyA.java:7)
at Mypackage.MyVector.add(MyA.java:22)
at Mypackage.MyA.main(MyA.java:63)java.lang.NullPointerException 网上差的可能是初始化的问题
我觉得是在第5行和第20行这两个语句出现了问题,为什么?
{
class Cell
{
//5 private Object data
private Cell next;
}
private static Cell _head;
public void add(Object data)
{
Cell p = new Cell();
//Cell p = new Cell();
if( _head == null)
p = _head;
else
p = getTail();
//20 p.data = data
}
//找到尾车厢
private Cell getTail()
{
Cell p = new Cell();
if(_head == null)
return _head;
p = _head;
while(p.next==null)
p = p.next;
return p;
}
public Object get(int n)
{
Cell p = new Cell();
p = _head;
for(int i = 0; i < n; i++)
{
p = p.next;
}
return p.data;
}
public int size()
{
return 0;
}
}
public class MyA
{
public static void main(String[] args)
{
MyVector v = new MyVector();
v.add("qqq");
v.add("aaa");
}
}
运行总会有错误:
Exception in thread "main" java.lang.NullPointerException
at Mypackage.MyVector$Cell.access$0(MyA.java:7)
at Mypackage.MyVector.add(MyA.java:22)
at Mypackage.MyA.main(MyA.java:63)java.lang.NullPointerException 网上差的可能是初始化的问题
我觉得是在第5行和第20行这两个语句出现了问题,为什么?
{
class Cell
{
//5 private Object data
private Cell next;
}
private static Cell _head;public void add(Object data)
{
Cell p = new Cell();
//Cell p = new Cell();
if( _head == null)
p = _head;
else
p = getTail();
//20 p.data = data
}
//找到尾车厢
private Cell getTail()
{
Cell p = new Cell();
if(_head == null)
return _head;
p = _head;
while(p.next==null)
p = p.next;
return p;
}
public Object get(int n)
{
Cell p = new Cell();
p = _head;
for(int i = 0; i < n; i++)
{
p = p.next;
}
return p.data;
}
public int size()
{
return 0;
}
}
public class MyA
{public static void main(String[] args)
{
MyVector v = new MyVector();
v.add("qqq");
v.add("aaa");
}
}
at Mypackage.MyVector.add(MyA.java:22)
at Mypackage.MyA.main(MyA.java:63)都已经明确指明了错误位置,不用猜测了