在python的 [xx:xx]
切片操作中快乐之后,返回Java变成发现这个习惯保持保持下去了!,可惜JDK并不认账反手给我爆了两个红JDK:这是别人的香水味!
所以这次总结一下在Java中各种数据类型的切片操作如何实现,给未来忘记如何操作的我一个笔记(未来的我:以前的你,真有你的!)
Array 数组
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 字符串
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 数组
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);
执行结果:
list的方法也是在实例化的对象上点一下出现subxxx的字样,那就是切片操作了
.subList(begin_index, end_index)
就是要把切片过后的list存放在另外一个list对象中会比较麻烦, 就和初始化list一样麻烦。。。
当然你如果没有存放切片之后的list的要求你也可以直接打印
System.out.println(test_list.subList(1, 4));
结果都是一样的
好了这就是关于在Java中的各种切片操作了,如果有什么别的更好的操作或者遗漏的操作欢迎评论区指正, 非常感谢您看完本篇文章, 如果对您有帮助,点一个大大的👍,将会激励我这个懒货走向生产队母猪化,非常感谢
作者:小阿宅哟
订正:暂无
补充:暂无