第一类
private Map<Integer, ArrayList<Question>> questions = new HashMap<Integer,ArrayList<Question>>()
public ArrayList<Question> getQuestions(int level) {
return new ArrayList<Question>(questions.get(level));
}第二类
private Map<Integer, ArrayList<Question>> questions = new HashMap<Integer,ArrayList<Question>>()
public ArrayList<Question> getQuestions(int level) {
return questions.get(level);
}经过运行测试结果是不同的,第一类没问题,第二类就不行了~
private Map<Integer, ArrayList<Question>> questions = new HashMap<Integer,ArrayList<Question>>()
public ArrayList<Question> getQuestions(int level) {
return new ArrayList<Question>(questions.get(level));
}第二类
private Map<Integer, ArrayList<Question>> questions = new HashMap<Integer,ArrayList<Question>>()
public ArrayList<Question> getQuestions(int level) {
return questions.get(level);
}经过运行测试结果是不同的,第一类没问题,第二类就不行了~
public class GenericTest { public static void main(String[] args) {
Test1 t1 = new Test1();
Test2 t2 = new Test2();
for (int i = 1; i < 6; i++) {
ArrayList<Question> v1 = new ArrayList<Question>();
ArrayList<Question> v2 = new ArrayList<Question>();
v1.add(new Question());
v1.add(new Question());
t1.put(i, v1);
v2.add(new Question());
t2.put(i, v2);
}
System.out.println(t1.getQuestions(1));
System.out.println(t2.getQuestions(1));
}
/* jdk 1.6
* ~output:
* [question:1, question:2]
* [question:3]
*/
}class Question {
private static int index = 1;
private int num;
public Question() {
num = index++;
}
@Override
public String toString() {
StringBuffer v = new StringBuffer();
v.append("question:");
v.append(num);
return v.toString();
}
}class Test1 {
private Map<Integer, ArrayList<Question>> questions = new HashMap<Integer,ArrayList<Question>>();
public void put(Integer key, ArrayList<Question> value) {
questions.put(key, value);
}
public ArrayList<Question> getQuestions(int level) {
return new ArrayList<Question>(questions.get(level));
}
}class Test2 {
private Map<Integer, ArrayList<Question>> questions = new HashMap<Integer,ArrayList<Question>>();
public void put(Integer key, ArrayList<Question> value) {
questions.put(key, value);
}
public ArrayList<Question> getQuestions(int level) {
return questions.get(level);
}
}