当前位置: 代码迷 >> J2SE >> 帮小弟我改下好吗?老是抛出错误
  详细解决方案

帮小弟我改下好吗?老是抛出错误

热度:28   发布时间:2016-04-24 14:13:51.0
帮我改下好吗?老是抛出异常
如题,谢谢了
//:   c12:E10_TypedContainer.java
//+M   java   E10_TypedContainer
/******************   Exercise   10   *****************
  *   Create   a   new   type   of   container   that   uses   a
  *   private   ArrayList   to   hold   the   objects.   Capture
  *   the   type   of   the   first   object   you   put   in   it,
  *   and   then   allow   the   user   to   insert   objects   of
  *   only   that   type   from   then   on.
  ***********************************************/
import   java.util.*;

class   X   {
private   String   str   =   "X ";
public   String   toString()   {
return   str;
}
}

class   Y   {
private   String   str   =   "Y ";
public   String   toString()   {
return   str;
}
}

class   Container   {
private   ArrayList   lst=   null;
public   void   add(Object   o)   {
Class   type   =   null;
if(lst   ==   null)   {
type   =o.getClass();
lst.add(o);
}   else   {
if(!type.isInstance(o))   {
System.out.println( "not   the   same   type! ");
return;
}else   {
lst.add(o);//这里异常。
}
}
}
public   String   toString()   {
String   result   =   "[ ";
Iterator   it   =   lst.iterator();
while(it.hasNext())   {
result   =   result   +   (it.next()).toString()   + ", ";
}
return   result   + "] ";
}
public   void   cleanup()   {
lst.clear();
}
}

public   class   E10_TypedContainer   {
public   static   void   main(String[]   args)
throws   Exception     {
Container   tc   =   new   Container();
for(int   i   =   0;i <8;i++)   {
tc.add(new   X());//这里异常。
tc.add(new   Y());
}
System.out.println(tc);
tc.cleanup();
for(int   i   =   0;i <8;i++)   {
tc.add(new   Y());
tc.add(new   X());
}
System.out.println(tc);
}
}
异常:
Exception   in   thread   "main "   java.lang.NullPointerException
at   Container.add(E10_TypedContainer.java:32)
at   E10_TypedContainer.main(E10_TypedContainer.java:60)


------解决方案--------------------
----------------------------------------------------
public void add(Object o) {
Class type = null;
if(lst == null) {
type =o.getClass();
lst = new ArrayList <Object> (); //沒有初始化
lst.add(o);
} else {
----------------------------------------------------
  相关解决方案