62,628
社区成员
发帖
与我相关
我的任务
分享
import java.util.ArrayList;
import java.util.List;
/**
* List遇到的问题.
* <p>
* <p>
* <p>
* Created by prd on 2016/03/10.
*/
public class Main {
public static void main(String[] args) {
List<List<String>> lists = new ArrayList<>();
List<String> newlists = new ArrayList<>();
for (int i = 0; i < 5; i++) {
/*
本意是在这里删除newlists里面的所有元素,
全部重新添加.
发现用了clear无效果,但将:
List<String> newlists = new ArrayList<>();
放在循环内则可正常运行.
*/
newlists.clear();
for (int j = 0; j < 10; j++) {
StringBuffer str = new StringBuffer();
str.append("this -> " + j + " , " + i);
newlists.add(str.toString());
}
lists.add(newlists);
}
for (int i = 0; i < lists.size(); i++) {
for (int j = 0; j < lists.get(i).size(); j++) {
System.out.println(lists.get(i).get(j));
}
System.out.println("-------------------------------");
}
}
}
import java.util.ArrayList;
import java.util.List;
/**
* List遇到的问题.
* <p>
* <p>
* <p>
* Created by prd on 2016/03/10.
*/
public class Main {
public static void main(String[] args) {
List<List<String>> lists = new ArrayList<>();
for (int i = 0; i < 5; i++) {
/*
本意是在这里删除newlists里面的所有元素,
全部重新添加.
发现用了clear无效果,但将:
List<String> newlists = new ArrayList<>();
放在循环内则可正常运行.
*/
List<String> newlists = new ArrayList<>();
//newlists.clear();
for (int j = 0; j < 10; j++) {
StringBuffer str = new StringBuffer();
str.append("this -> " + j + " , " + i);
newlists.add(str.toString());
}
lists.add(newlists);
}
for (int i = 0; i < lists.size(); i++) {
for (int j = 0; j < lists.get(i).size(); j++) {
System.out.println(lists.get(i).get(j));
}
System.out.println("-------------------------------");
}
}
}

楼主对于"对象"或者说"类的实例"概念还比较模糊。
这样说吧,在这段程序代码中,有几个new就有几个对象。
假如把newList放在外面,那么实际上你只new了两个对象。
而假如放在里面,那就是十一个对象。
其中一个对象是外层循环
在错误的结果里,内层循环始终都是一个值,因为它只有一个对象。
而在正确的结果里,内层循环是十个值,因为它有十个对象。
实际上调用clear方法在这个程序里没有意义。