1. List of List使用规范
List<List<Integer>> list = new List<List<Integer>>() //错误写法,因为List是接口,不能实例化(Cannot instantiate the type List<List<Integer>>)。
List<List<Integer>> list = new ArrayList<ArrayList<Integer>>(); //错误写法,会报错:类型无法转换
List<LinkedList<Integer>> list = new LinkedList<LinkedList<Integer>>();//正确写法
List<List<Integer>> list = new LinkedList<List<Integer>>(); //正确写法
List<List<String>> ans = new ArrayList<>(); //正确写法
综上可得,定义列表套列表时泛型的类型参数必须相同或者类似于new ArrayList<>();这种写法不定义泛型, 这种情况下会默认和前面的泛型保持一致,也是正确的写法
2. List of List深入解析
import java.util.ArrayList;
import java.util.List;
public class test {
public static void main(String[] args) {
List<List<String>> ans = new ArrayList<>();
List<String> tmp = new ArrayList<>();
tmp.add("aa");
ans.add(tmp);
System.out.println("ans is: ");
System.out.println(ans); //result 1. [[aa]]
tmp.clear();
tmp.add("bb");
ans.add(tmp);
System.out.println("ans is: ");
System.out.println(ans); //result 2. [[bb], [bb]]
}
}
注意上述代码中的result 2, 使用过程中需要注意, 列表a连续将列表b add()了多次的情况下,只要列表b发生了变化, 列表a中所有子列表都会随之变化。 所以在有些我们不希望列表a中前面已经添加好的子列表变化的场景下,写代码或者算法题时这里应该创建一个新的临时列表存储每一个时刻的b列表的值。
import java.util.ArrayList;
import java.util.List;
public class test {
public static void main(String[] args) {
List<List<String>> ans = new ArrayList<>();
List<String> tmp = new ArrayList<>();
tmp.add("aa");
List<String> new_temp = new ArrayList<>();
new_temp.add(temp.get(0));
//ans.add(tmp);
ans.add(new_tmp);
System.out.println("ans is: ");
System.out.println(ans); //result 1. [[aa]]
tmp.clear();
tmp.add("bb");
List<String> new_temp = new ArrayList<>();
new_temp.add(temp.get(0));
ans.add(new_temp); //result 2. [[aa], [bb]]
System.out.println("ans is: ");
System.out.println(ans);
}
}
上面的例子往往用于for循环不断修改tmp列表的值并且需要将新列表的值add到ans列表中。
本文探讨了Java中List<List>的使用规范,强调了泛型类型的统一,并指出当一个列表被多个列表引用时,修改操作可能导致所有引用者同步变化的问题,提醒开发者在特定场景下需创建临时列表以防止意外的变动。
&spm=1001.2101.3001.5002&articleId=106866374&d=1&t=3&u=afd24e0da06243a4bc6c6f879c4d286e)

被折叠的 条评论
为什么被折叠?



