在java集合中,常用ArrayList类中,若需要对 list进行截取,可以使用subList方法,进行生成 SubList的内部类,那么 ArrayList 和 内部类 ArrayList$SubList 有啥区别和关联呢?ArrayList 和 SubList 分别进行操作时候(增、删、改),对原来是 有影响变化吗?
java.util.ArrayList.SubList 如下:
- /**
- * Description: subList 方法测试
- * @return void
- * @version v1.0
- * @author wu
- * @date 2022/11/14 10:43
- */
- @Test
- public void subListMethodTest() throws Exception {
- final ArrayList
srcList = Lists.newArrayList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); - final List
subList = srcList.subList(2, 5); - System.out.println("srcList :" + srcList);
- System.out.println("subList :" + subList);
- }
- srcList :[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- subList :[3, 4, 5]
1.2、根据输出结果可知:根据索引截取,前闭后开 [startIndex,endIndex) ;
- @Test
- public void srcListTest() throws Exception {
- final ArrayList
srcList = Lists.newArrayList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); - final List
subList = srcList.subList(2, 5); - System.out.println("srcList :" + srcList);
- System.out.println("subList :" + subList);
-
- /**
- * 添加和删除,会触发 ConcurrentModificationException 异常
- * 原因: 会修改 modCount 属性
- */
- srcList.add("333");
- System.out.println("srcList add :" + srcList);
- // System.out.println("subList :" + subList);
-
- // srcList.remove("3");
- // System.out.println("srcList remove :" + srcList);
- // System.out.println("subList :" + subList);
-
- /**
- * 修改是正常操作,不会修改 modCount 属性 ;
- * srcList 修改后, subList 会同步修改
- */
- // srcList.set(6,"666");
- // srcList.set(3,"333");
- // System.out.println("srcList update :" + srcList);
- // System.out.println("subList :" + subList);
- }
- @Test
- public void subListTest() throws Exception {
- final ArrayList
srcList = Lists.newArrayList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"); - final List
subList = srcList.subList(2, 5); - System.out.println("srcList :" + srcList);
- System.out.println("subList :" + subList);
-
- subList.add("101");
- // System.out.println("srcList :" + srcList);
- // System.out.println("subList add:" + subList);
-
- // subList.remove("3");
- // System.out.println("srcList :" + srcList);
- // System.out.println("subList remove:" + subList);
-
- subList.set(0, "333");
- System.out.println("srcList :" + srcList);
- System.out.println("subList update:" + subList);
- }
3.1、 输出结果,测试过程略。
上述规则,请自行执行【二-代码示例】中的代码,进行验证。
- String s = "12345678910";
- final String substring = s.substring(2, 5);
- System.out.println("substring=" + substring);
-
- //输出结果:substring=345
更多的有关 java list 集合文章:
https://thinkcode.blog.csdn.net/article/details/126111603
https://thinkcode.blog.csdn.net/article/details/126111838