本帖最后由 黑马张涛 于 2012-8-29 16:41 编辑
- import java.util.ArrayList;
- import java.util.Iterator;
- public class BugTest {
-
- public static void main(String[] args) {
-
- //该方法输出的报异常
-
- BB b = new BB(true,true);
-
- b.start();
-
- BB c = new BB(true,false);
-
- c.start();
-
- //正确输出的方法
-
- AA a = new AA();
-
- a.setA(true);
-
- a.start();
-
- }
- }
- class BB{
-
- private ArrayList<String> alist;
-
- private ArrayList<String> blist;
-
- private boolean isA = false;
- private boolean isB = false;
-
- BB(boolean isA,boolean isB)
- {
- this.isA=isA;
- this.isB=isB;
- }
- void start()
- {
- if(isA)
- {
- alist=new ArrayList<String>();
- newAddPrint(alist);
- }
- if(isB)
- {
- blist=new ArrayList<String>();
- newAddPrint(blist);
- }
- System.out.println(alist instanceof ArrayList);
- System.out.println(blist instanceof ArrayList);
- }
-
-
- void newAddPrint(ArrayList<String> list){
-
- addList(list); // 用你的方法调用创建对象的方式,我在addList之前加 instanceof 判断语句显示alist或blist都还不是ArrayList实例,我觉得可能是Jvm执行顺序决定的
-
- printList(list);
-
- }
- void addList(ArrayList<String> list){
-
- list.add("1");
-
- list.add("2");
-
- list.add("3");
-
- }
-
-
- void printList(ArrayList<String> list){
-
- Iterator<String> it = list.iterator();
-
- String s;
-
- while(it.hasNext()){
-
- s = it.next();
-
- System.out.println(s);
-
- }
-
- }
-
- }
复制代码 |