java中List.subList方法使用注意

AFSim 2.9中文手册实战指南:从安装到高级功能详解(附B站视频链接) 本文详细介绍了AFSim 2.9的安装配置、基础功能操作和高级功能应用,帮助用户快速掌握这款强大的仿真平台。从系统要求检查到多体动力学仿真,再到性能优化技巧,全面解析AFSim 2.9的使用方法,适合初学者和进阶用户参考。 阅读详情

本文转自:http://topic.csdn.net/u/20110830/13/7ea0e09c-7317-4215-96ab-fa672ea91ff8.html?91324


For example, ArrayList<Integer> aList;

获取其子链表 List<Integer> sub = aList.subList(begin, end);

sub可以继续转换成ArrayList, ArrayList<Integer> aSub = new ArrayList<Integer>(sub);

如果你使用 ArrayList<Integer> aSubList = (ArrayList<Integer>)aList.subList(begin, end);

会产生异常,因为List转换成ArrayList 是不允许的 (父类转换成子类是不允许的,因为会有数据丢失)

 

 

说明:我写此的目的不是为了抨击jdk的不好,而是为了说明这个地方可能人为引发误解。
在使用集合中,可能常常需要取集合中的某一部分子集来进行一下操作,于是subList这个方法就映入我们的眼帘,毫不犹豫地使用。

例如以下代码:

Java code
public  static  void  main( final  String[] args) { List < Object >  lists  =  new  ArrayList < Object > (); lists.add( " 1 " ); lists.add( " 2 " ); lists.add( " 3 " ); lists.add( " 4 " ); List < Object >  tempList  = lists.subList( 2 , lists.size()); tempList.add( " 6 " ); System.out.println(tempList);  //  1 System.out.println(lists);  //  2  }
 

代码初步写好后,可能我们想达到的效果是:往集合lists的子集合tempList中添加一个元素6,而原有的集合保持不变。

即到达这样的效果:lists = [1, 2, 3, 4],tempList = [3, 4, 6]。但是我们看到实际的结果确是lists里边也添加了元素6。

这是怎么一会事呢,通过查找java原代码我们可以看到:tempList的subList实现代码在AbstractList类里边,然而无论如何,最终的结果都是返回一个AbstractList的子类:SubList(该类是一个使用默认修饰符修饰的类,其源代码位于AbstractList.java类文件里边),

SubList类的构造方法:

Java code
SubList(AbstractList < E >  list,  int  fromIndex,  int  toIndex) {  if  (fromIndex  <  0 )  throw  new IndexOutOfBoundsException( " fromIndex =  "  +  fromIndex);  if  (toIndex  >  list.size())  throw  new IndexOutOfBoundsException( " toIndex =  "  +  toIndex);  if  (fromIndex  >  toIndex)  throw  new IllegalArgumentException( " fromIndex( "  +  fromIndex  +  " ) > toIndex( "  +  toIndex  +  " ) " ); l  =  list; offset  =  fromIndex; size  =  toIndex  -  fromIndex; expectedModCount  =  l.modCount; }

 

  因此,当我们使用子集合tempList进行元素的修改操作时,会影响原有的list集合。所以在使用subList方法时,一定要想清楚,是否需要对子集合进行修改元素而不影响原有的list集合。

如果需要对子集合的元素进行修改操作而不需要影响原集合时,我们可以使用以下方法进行处理:
Java code
public  static  void  main( final  String[] args) { List < Object >  lists  =  new  ArrayList < Object > (); lists.add( " 1 " ); lists.add( " 2 " ); lists.add( " 3 " ); lists.add( " 4 " );  // 注意这里是和本文顶部的代码不同的....  List < Object >  tempList  =  new  ArrayList < Object > (lists.subList( 2 , lists.size())); tempList.add( " 6 " ); System.out.println(tempList);  //  1  System.out.println(lists);  //  2  }
智能汽车嘚啵嘚 --- 智能座舱第七稿:智能座舱的升级OTA 阅读详情

相关推荐

Elsevier投稿实战:从ESWA模板到录用通知的全流程拆解

本文详细拆解了Elsevier旗下期刊ESWA(Expert Systems With Applications)的投稿全流程,从模板选择、投稿系统操作到审稿意见回复和录用后注意事项。重点分享了单栏LaTeX模板调整、APA文献格式处理、Highlights撰写技巧等实战经验,帮助研究者高效完成投稿并提升录用概率。

weixin_32715349的博客 263

ArrayList之SubList源码解析

subList是ArrayList的内部类, public List<E> subList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); } subListRang...

root 975

Apache Doris集群IP变更急救指南:用Docker容器+priority_networks快速恢复FE/BE节点

本文详细介绍了Apache Doris集群在IP变更情况下的应急处理方案,通过Docker容器和priority_networks配置快速恢复FE/BE节点。文章提供了从容器化环境构建、元数据迁移到生产环境切换的全流程指南,帮助运维团队在30分钟内完成集群恢复,显著减少停机时间。

pink7的博客 119

Java的List之坑系列--subList与原始List相互影响

本文介绍Java中的List的几个注意问题,包括:List#subList(获取子list)、Collections#unmodifiableList(不可修改的List)。

IT利刃出鞘的博客 5312

拜耳阵列(Bayer Pattern)以及常见彩色滤波矩阵(CFA)

本文介绍了拜耳阵列的工作原理(Bayer Pattern)以及常用的彩色滤波矩阵(CFA)

风一样的男子(quinta)的博客 7136

基于STM32、HAL库的GZP6816D气压传感器 驱动程序设计

测量范围:0-16kPa(可根据型号不同有变化)工作电压:1.8V-3.6V。高精度:±1% FS。

corlin6688的博客 226

C#3.0的新特性

/**============================主要演示C#3.0的新特性=====================*一、自动属性*二、对像和集合初始化器*三、扩展方法*四、Lambda表达式* 13/6/2010 Berlin**/using System;using System.Collections.Generic;using System.Linq;us...

weixin_30552811的博客 192

【2026年米哈游春招 - 3月14日 -第一题- 行列相等】(题目+思路+Java&C++&Python解析+在线测试)

摘要 本文解决了一个矩阵行列和匹配问题:统计矩阵中行和等于列和的所有行列对数量。算法首先计算每行和每列的元素和,然后利用哈希表统计各行列和的出现次数。通过遍历列和并查询对应的行和出现次数,高效计算出匹配对数。该方法时间复杂度为O(nm),空间复杂度为O(n+m),适用于大规模矩阵数据。代码实现了Python、Java和C++版本,通过哈希表优化避免了暴力枚举,显著提高了计算效率。

m0_73659489的博客 84

javaAPI深入理解(1)如何截短一个List以及List.subList()方法的坑

removeRange(int, int);这个方法AbstractList并没有暴露出来,我们应该如何得到一个截短的list?1 如何得到一个list某个范围的子集sublist首先想到sublist(int, int)方法 注意此方法参数左闭右开。 测试如下1.1 修改sublist会影响原来的list LinkedList<String> ll = new LinkedList<>(

kkgbn的博客 4万+

基于深度学习的行人车辆检测与计数系统(UI界面+YOLOv8/v7/v6/v5代码+训练数据集)

从YOLOv1到最新的YOLOv8,其网络结构、训练策略和损失函数不断优化,性能持续提升。image_path, _ = QFileDialog.getOpenFileName(self, "选择图片文件", "", "Image Files (*.jpg *.png *.jpeg *.bmp)")video_path, _ = QFileDialog.getOpenFileName(self, "选择视频文件", "", "Video Files (*.mp4 *.avi *.mov *.mkv)")

YOLO 232

教你写出高质量SQL(实践必备)

1、查询SQL尽量不要使用select * ,而是select具体字段。 //反例子 select * from sys_user; //正例子 select id,name from sys_user; 理由: 只取需要的字段,节省资源、减少网络开销;select * 进行查询时,很可能就不会使用到覆盖索引,就会造成回表查询; 覆盖索引:只需要在一棵索引树上就能获取SQL所需的所有列数据,无需回表,速度更快。 例如: 回表查询:先通过普通索引的值定位聚簇索引值,再通过聚簇索引的值定位行记..

ANGEL CITY 1万+

java之深入理解List.subList()方法

removeRange(int, int);这个方法AbstractList并没有暴露出来,我们应该如何得到一个截短的list? 1 如何得到一个list某个范围的子集sublist 首先想到sublist(int, int)方法  注意此方法参数左闭右开。  测试如下 1.1 修改sublist会影响原来的list LinkedList<String> ll = new Lin...

别抢我蓝buff 1955

Python散点图(Scatter Plot):高阶分析、散点图矩阵、三维散点图及综合应用

散点图作为一种直观且功能强大的数据可视化工具,在数据分析中具有广泛的应用。通过观察散点图中数据点的分布模式,我们可以轻松地判断变量之间是否存在相关性,以及相关性的类型和强度。同时,散点图也是识别数据集中异常值的有效工具,无论是通过直观观察还是结合统计方法,都能帮助我们发现数据中的异常情况。掌握散点图的绘制和分析技巧,将使我们在数据探索和决策制定中更加得心应手。

SiArch的博客 1447

Java中List的subList()方法及使用注意事项

其中subList(0, 5)取得的是下标为0到4的元素,不包含下标为5的元素.java.util.List中的subList方法返回列表中指定的 fromIndex(包括 )和 toIndex(不包括)之间的部分视图。 fromIndex - subList 的低端(包括) toIndex - subList 的高端(不包括)此方法省去了显式范围操作(此操作通常针对数组存在)。通过传递 subList 视图而非整个列表,期望列表的任何操作可用作范围操作。例如,下面的语句从列表中移除了元素的范围: 下面通过

qq_43842093的博客 3万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Java中的List.subList方法注意事项

ArrayList的subList结果不可强转成ArrayList,否则会抛出ClassCastException 异常,即 java.util.RandomAccessSubList cannot be cast to java.util.ArrayList. 说明:subList 返回的是 ArrayList 的内部类 SubList,并不是 ArrayList ,而是 ArrayList ...

大漠孤烟的博客 3177

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

java int index_java中 List.subList(int fromIndex, int toIndex)方法需要注意的问题

关于集合类,《阿里巴巴Java开发手册》中有一个规定: 这里我们简单分析下。subListsubList是List接口中定义的一个方法,该方法主要用于返回一个集合中的一段、可以理解为截取一个集合中的部分元素,他的返回值也是一个List。如以下代码:public static void main(String[] args) {List names = new ArrayList() {{add(...

weixin_42363154的博客 353

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

java sublist 用法_java.util.List接口的方法subList()的使用注意事项

JDK中,List接口有一个实例方法List subList(int fromIndex, int toIndex),其作用是返回一个以fromIndex为起始索引(包含),以toIndex为终止索引(不包含)的子列表(List)。但值得注意的是,返回的这个子列表的幕后其实还是原列表;也就是说,修改这个子列表,将导致原列表也发生改变;反之亦然。下面是一段实例代码:Java代码importja...

weixin_36081891的博客 350

java中 List.subList(int fromIndex, int toIndex)方法需要注意的问题

关于集合类,《阿里巴巴Java开发手册》中有一个规定: 这里我们简单分析下。 subList subList是List接口中定义的一个方法,该方法主要用于返回一个集合中的一段、可以理解为截取一个集合中的部分元素,他的返回值也是一个List。 如以下代码: public static void main(String[] args) { List<String> names = new ArrayList<String>() {{ add.

Dream It Possible 3862

java.util.List接口的方法subList()的使用注意事项

JDK中,List接口有一个实例方法List<E> subList(int fromIndex, int toIndex), 其作用是返回一个以fromIndex为起始索引(包含),以toIndex为终止索引(不包含)的子列表(List)。 但值得注意的是,返回的这个子列表的幕后其实还是原列表; 也就是说,修改这个子列表,将导致原列表也发生改变;反之 父的list改变会影响子的li...

那些年的代码 70

import java.util.list报错_java.util.List接口的方法subList()的使用注意事项

JDK中,List接口有一个实例方法List subList(int fromIndex, int toIndex),其作用是返回一个以fromIndex为起始索引(包含),以toIndex为终止索引(不包含)的子列表(List)。但值得注意的是,返回的这个子列表的幕后其实还是原列表;也就是说,修改这个子列表,将导致原列表也发生改变;反之 父的list改变会影响子的list失效,报错public ...

weixin_36132709的博客 901

java.util.List接口的方法subList()的说明及使用注意事项

JDK中,List接口有一个实例方法List&lt;E&gt; subList(int fromIndex, int toIndex),其作用是返回一个以fromIndex为起始索引(包含),以toIndex为终止索引(不包含)的子列表(List)。  一、subList简述    原型:List&lt;E&gt; subList(int fromIndex,int toIndex)      1...

道阻且长,行则将至 4876
上一篇: EasyMock tutorial – Getting Started
下一篇: Java多线程-工具篇-BlockingQueue
louis9212
博客等级 码龄14年 8粉丝 49原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址