Java Array、String、List的切片操作

Array数组

copy
int[] test_int = new int[] { 1, 2, 3, 4, 5};
test_int = Arrays.copyOfRange(test_int, 1, 4);
System.out.println(Arrays.toString(test_int));

使用的是 Arrays里面的copyOfRange(被切片的数组, begin_index, end_index)

这里的 begin_index, end_index 对应 Python中 [begin_index: end_index]

遵循 左闭右开 之后的方法也都是遵循这个不再重复

String 字符串

copy
String test_string = "12345";
test_string = test_string.substring(1, 4);
System.out.println(test_string);

在这三个类型中 只有 数组需要调用Arrays类中的方法,在字符串和list 均是调用了实例化的方法,直接在实例化的后面 "."一下 加上字母 “sub”就会出先对应的方法

.substring(begin_index, end_index)

List 数组

copy
ArrayList<Integer> test_list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
ArrayList<Integer> test_list_2 = new ArrayList<>(test_list.subList(1, 4));
System.out.println(test_list_2);

ist的方法也是在实例化的对象上点一下出现subxxx的字样,那就是切片操作了

.subList(begin_index, end_index)

就是要把切片过后的list存放在另外一个list对象中会比较麻烦, 就和初始化list一样麻烦。。。

当然你如果没有存放切片之后的list的要求你也可以直接打印

copy
System.out.println(test_list.subList(1, 4));
posted @   离人怎挽_wdj  阅读(1223)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义

点击右上角即可分享
微信分享提示