您的位置:首页 > 理论基础 > 数据结构算法

Java数据结构那些事儿--列表套列表(List of List)

2020-07-15 06:16 411 查看

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列表中。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: