Java集合类交换两个位置的元素Collections.swap()方法详解

【MBD开发】Simulink中的枚举 01 什么是枚举 按百度百科的词条【枚举】是在编程语言中用来存储一组固定的常量。不同编程语言的枚举语法也不一样,以C语言为例。 typedef enum{ GEAR_P, //0:P挡 GEAR_R, //1:倒挡 GEAR_N, //2:空挡 GEAR_D, //3:前进}_GEAR; 上面枚举了一个_GEAR数据,用GEAR_P表示0,GEAR_R表示1……​​​​​​​ if(current_gear==GEAR.. 阅读详情
AI摘要

本文详细解析了Java中使用Collections.swap方法交换集合元素的源码实现,并通过具体示例展示了其工作原理。文章强调了swap方法内部逻辑及可能引发的异常情况。

目录

1.先来源码:

2.测试过程如下:


集合交换元素使用Collections.swap(List<?> list, int i, int j);

1.先来源码:

逻辑比较简单,注意 l.set(j, l.get(i)) 方法返回的是集合该位置原来的值。

    /**
     * Swaps the elements at the specified positions in the specified list.
     * (If the specified positions are equal, invoking this method leaves
     * the list unchanged.)
     *
     * @param list The list in which to swap elements.
     * @param i the index of one element to be swapped.
     * @param j the index of the other element to be swapped.
     * @throws IndexOutOfBoundsException if either <tt>i</tt> or <tt>j</tt>
     *         is out of range (i &lt; 0 || i &gt;= list.size()
     *         || j &lt; 0 || j &gt;= list.size()).
     * @since 1.4
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void swap(List<?> list, int i, int j) {
        // instead of using a raw type here, it's possible to capture
        // the wildcard but it will require a call to a supplementary
        // private method
        final List l = list;
        l.set(i, l.set(j, l.get(i)));
    }

2.测试过程如下:

import java.util.ArrayList;
import java.util.Collections;

public class SwapDemo {
    public static void main(String[] args) {
        ArrayList<Object> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        System.out.println(list);

        Collections.swap(list, 0, 1);
        System.out.println(list);
    }
}

输入结果如下:可以看到前两个元素的位置已完成交换。

[1, 2, 3]
[2, 1, 3]

Process finished with exit code 0

 

Stata中介效应分析实战:从sgmediation安装到Sobel检验结果解读 本文提供了Stata中进行中介效应分析的完整实战指南,重点介绍了第三方命令sgmediation的安装、配置与使用。通过详细案例演示了如何运用Sobel检验分析变量间的间接效应,并深入解读检验结果,帮助研究者厘清自变量影响因变量的具体路径。文章还探讨了Sobel检验的原理、优缺点及结果报告规范,是进行实证研究的实用参考。 阅读详情

相关推荐

【Godot】实现对话系统

在 Godot 中实现对话系统(Dialogue System)是游戏开发中的常见需求。Godot本身自带的的灵活性和轻量级脚本语言 GDScript 使得实现对话系统变得相对简单。以下是实现一个基础对话系统的示例。(语言为GDScript但高亮选择Python因为类似)通过 Godot 和 GDScript,我们可以给我们的游戏实现一个对话系统。从简单的文本显示到复杂的分支对话,Godot 提供了足够的灵活性来满足我们的需求。如果需要更高级的功能,可以尝试使用现成的插件如 Dialogic。

Octopus2077的博客 2531

Java Collections.swap()方法

作用: 交换List集合中任意两个元素的位置 代码: import java.util.ArrayList; import java.util.Collections; public class SwapElements { public static void main(String[] args) { ArrayList arrayList = new ArrayList(); arrayList.add("A"); arrayList.add("B");

巴德不说话的博客 9599

阿里云一键登录Java后端实战:5分钟搞定号码认证服务集成(附完整代码)

本文详细介绍了如何在Java后端项目中快速集成阿里云号码认证服务(PNVS),实现高效、安全的一键登录功能。文章从核心架构、安全机制解析入手,提供了完整的Maven依赖配置、服务端环境准备、核心业务逻辑实现(包括Token验证、用户处理、异常降级)以及生产环境下的性能优化、监控与部署方案,并附有可直接使用的完整代码示例。

p1q2r的博客 858

Java Collections swap()方法具有什么功能呢?

Java Collections swap()方法的功能简介说明

qq_25073223的博客 2325

Vivado工程芯片型号更换全流程:从IP更新到生成新bit文件(避坑指南)

本文详细介绍了Vivado工程中更换芯片型号的全流程,包括IP更新、约束文件适配和生成新bit文件的关键步骤。特别针对FPGA开发中常见的兼容性问题提供避坑指南,帮助开发者高效完成芯片迁移,确保设计稳定性和性能优化。

weixin_42549451的博客 303

Collections.swap方法

由上,可传入的数组类型分别为Object[] 和List类型的数组。用于交换数组中,对应两个元素的位置。

m0_51973634的博客 441

llama.cpp 参数调优大全(4060 最优配置)

本文针对NVIDIA RTX 4060(8GB显存)显卡,提供了llama.cpp参数调优的实战指南。核心策略是采用小模型(7B/8B)配合Q4_K_M量化,通过合理设置GPU层数(-ngl 28)、上下文长度(-c 2048)和批量大小(-b 512)来平衡性能和显存占用。重点推荐启用flash-attn加速和mlock内存锁定,并给出标准、高性能和保守三种配置方案。调优优先级为:GPU利用率>吞吐量>显存>线程数,同时警示避免常见错误如过大上下文或GPU层数设置。最终推荐4060最佳配置为7B Q4_

刘一说的IT专栏 3418

Java Collections swap()方法与示例

集合类swap()方法 (Collections Class swap() method) swap() method is available in java.util package. swap()方法在java.util包中可用。 swap() method is used to swap the element at index f1 with the element at index ...

3908

【NodeRed】node-red-contrib-opcua实现PLC读写

在之前的博文【Node-RED】node-red-contrib-opcua-server模块使用(1)中,我们介绍了用node-red-contrib-opcua-server模块实现OPCUA服务端的,以及二次开发的内容。本节博文中我们采用官方社区自带的node-red-contrib-opcua组件开展对OPCUA客户端的介绍,详细阐述用该组件中OpcUa-Client节点实现客户端对PLC的读写,以及实现过程中遇到的问题。由于官方社区中并没有找到该组件的介绍实例,这也是本博文编写的第1个原因。

weixin_48618536的博客 963

SAP 与 Palantir 合作全景解析:这不是普通集成,而是把 ERP、数据语义层、云迁移与企业级 AI 串成一条价值链

SAP与Palantir的战略合作聚焦企业数字化转型核心痛点,通过深度技术整合构建"数据-决策-执行"闭环。合作包含四大主线:云迁移连续性保障、SAP业务数据云与Palantir平台对接、联合工程开发、高监管行业优先落地。技术实现上采用SAP认证插件,支持双向数据交互和实时业务动作触发。该合作突破了传统ERP系统局限,将业务语义与AI执行相结合,特别适合制造业供应链优化、财务争议处理等高价值场景,为企业在云迁移过程中实现业务连续性与智能化升级提供新范式。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 200

Collections.工具类,的基本用法

Collections.sort(List<> list):根据元素的自然顺序 对指定列表按升序进行排序。 Collections.max():根据元素的自然顺序,返回给定 collection 的最大元素。 Collections.min():根据元素的自然顺序 返回给定 collection 的最小元素。 Collections.swap(List,i,j):在指定列表的指定位置处交换元素。 Collections.addAll(): 代码: package day20200819; im

qq_43472248的博客 294

真正的工业级环形缓冲区(Circular Buffer)完整实现细节

永远不要永远不要ToArray()或AddRange()永远返回或两段Span永远用_head_tail% Capacity实现环形照着上面这套代码改,你的系统将彻底告别内存爆炸,从“实验室玩具”变成“产线战神”!需要我给你一个支持两段绘制的完整实现吗?

专注于前沿技术的探索与实践,热衷于从代码逻辑、架构设计到行业应用等多维度深挖技术本质。期待在技术之路上与你共同成长~ 130

list交换元素位置 java_Java集合类交换两个位置的元素Collections.swap()方法详解

目录1.先来源码:2.测试过程如下:集合交换元素使用Collections.swap(List> list, int i, int j);1.先来源码:逻辑比较简单,注意 l.set(j, l.get(i)) 方法返回的是集合该位置原来的值。/*** Swaps the elements at the specified positions in the specified list.* (...

weixin_42510900的博客 1162

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

List元素互换,List元素转换下标,Java Collections.swap()方法实例解析

Java Collections.swap()方法解析 jdk源码: public static void swap(List<?> list, int i, int j) { // instead of using a raw type here, it's possible to capture // the wildcard but it will require a call to a supplementary // private me

了迹奇有没 2093

深度学习工具包 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")

java.util.Collections.swap()方法实例

java.util.Collections.swap()方法实例 歪脖小新 swap(List<?>, int, int)方法被用于交换在指定列表中的指定位置的元素。 声明 以下是java.util.Collections.swap()方法的声明。 public static void swap(List<?> list,int i,int j) 参数 list--在该列表中的调剂元素。 i--要交换的一个元素的索引。 j--要交换...

cxu123321的博客 1815

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

java swap的作用_Java Collections swap()方法与示例

集合类swap()方法swap()方法在java.util包中可用。swap()方法用于将给定列表(l)中索引为f1的元素与索引为f2的元素交换。swap()方法是一个静态方法,可以通过类名进行访问,如果尝试使用类对象访问该方法,那么也不会出现任何错误。swap()方法在分配索引时可能会引发异常。IndexOutOfBoundsException:当给定索引f1或f2不在范围内时,可能引发此异常。...

weixin_36299482的博客 1900

swap()方法

java java version "1.8.0_172" Java(TM) SE Runtime Environment (build 1.8.0_172-b11) Java HotSpot(TM) 64-Bit Server VM (build 25.172-b11, mixed mode) 在Collections类里 /** * Swaps the elements at the...

DieJugend的博客 1013

java交换List中的两个元素

java中除了可以使用数组交换元素之外,还可以使用Collections交换List中对应两个下标的元素: import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Solution{ public static void main(String[] arg...

二哈 4940

Java Collections交换Arraylist元素位置

Arraylist 可以很方便的 add 、remove 其中的元素。 如果需要交换元素位置,该怎么操作呢? 可以把要交换的两个元素先按照需要的顺序 add 进来,再 remove 掉。但是,这样看着很别扭。 有没有好一点的方法呢? 有的,用 Collections 。 package container; import java.util.ArrayList; import java.util.Collections; public class SwapArrayList { public

weixin_44021334的博客 5821

java swap_Java Collections swap()用法及代码示例

java.util.Collections类的swap()方法用于交换指定列表中指定位置的元素。如果指定位置相等,则调用此方法将使列表保持不变。用法:public static void swap(List list, int i, int j)参数:此方法将以下参数作为参数list –交换元素的列表。i –要交换的一个元素的索引。j –要交换的其他元素的索引。异常如果i或j超出范围(i = li...

weixin_29638241的博客 551

java将list中的某个元素移动位置

本文介绍了如何使用Java将List中的某个元素移动到指定的位置。通过使用方法交换元素的位置,我们可以轻松实现元素位置的移动。这个方法对于实现特定的列表排序或调整元素顺序非常有用。

牛肉胡辣汤 2651

Java交换列表中两个元素的位置-Collections.swap()使用和一次误用

这样写完后代码都提了,转念一想显然是不对的

欧阳方超的专栏 1280

java string swap_java.util.Collections.swap()方法实例

java.util.Collections.swap()方法实例swap(List>, int, int)方法被用于交换在指定列表中的指定位置的元素。声明以下是java.util.Collections.swap()方法的声明。public static void swap(List> list,int i,int j)参数list--在该列表中的调剂元素。i--要交换的一个元素的...

weixin_35084652的博客 203

Collections中的方法

Collections中的方法 Collections: 面试题:Collection和Collections有什么区别? Collection是集合体系的最顶层,包含了集合体系的共性 Collections是一个工具类,方法都是用于操作Collection 方法: 1.static void swap(List list, int i, int j) :将指定列表中的两个...

云飞扬°的博客 2207

Java集合工具类Collections常用方法详解

文章目录1、Collections介绍2、Collections常用方法2.1、reverse()2.2、sort()2.3、swap()2.4、min()和max()2.5、copy()2.6、fill()2.7、replaceAll()2.8、shuffle()2.9、rotate()2.10、indexOfSubList()和lastIndexOfSubList()2.11、unmodifiableXxx() 1、Collections介绍     &nbsp

Code皮皮虾的博客 2507
上一篇: ArrayList的trimToSize方法详解
下一篇: 《学会提问》读书笔记分享
蓝关故人
博客等级 码龄9年 67粉丝 106原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址