我试图获取列表的子列表但由于某种原因,子列表仅打印 4项而不是8项。
String s1 = "{{ (( 4 + 5 )) }}";
System.out.println("Length of string = " + s1.length());
String[] s2 = s1.split(""); //Split the string into array
ArrayList al = new ArrayList(Arrays.asList(s2)); //Convert the array into list
al.remove(0); //remove the first occurence
TreeSet hs = new TreeSet(al.subList(1, 8)); //Create a hashset with only first 8 elements
输出
Length of string = 17
al list = [{, {, , (, (, , 4, , +, , 5, , ), ), , }, }]
length of the list= 17
al list subset = [ , (, 4, {]
length of the al subset= 4
答案 0 :(得分:1)
这是因为你正在使用Set数据类型。集不允许重复。打印的4个项目是您示例中索引1 - 8中唯一的4个唯一元素。
答案 1 :(得分:1)
第一件事是你只抓取7个项目,而不是8个。此外,你可能想查看TreeSet
的构造函数,看看构造函数中的重复值会发生什么。掠夺者,他们不会重复: - )
System.out.println("al after removal: " + al);
List<String> a2 = (List<String>) al.subList(1, 8);
System.out.println("Size of a2: " + a2.size());
System.out.println("a2: " + a2);
输出:
移除后al:[{,,((,(,, 4 ,, + ,, 5 ,,),),},}] 尺寸a2:7
a2:[,(,(,, 4 ,, +]