Arraylist 交换元素 [英] Arraylist swap elements

查看:30
本文介绍了Arraylist 交换元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何交换 ArrayList 的第一个和最后一个元素?我知道如何交换数组的元素:设置一个临时值来存储第一个元素,让第一个元素等于最后一个元素,然后让最后一个元素等于存储的第一个元素.

How do I swap the the first and last elements of an ArrayList? I know how to swap the elements of an array: setting a temporary value to store the first element, letting the first element equal the last element, then letting the last element equal the stored first element.

int a = values[0];
int n = values.length;
values[0] = values[n-1];
values[n-1] = a;

那么对于 ArrayList 会是这样吗?

So for an ArrayList<String> would it be like this?

String a = words.get(0);
int n = words.size();
words.get(0) = words.get(n-1);
words.get(n-1) = a

推荐答案

你可以使用 Collections.swap(List list, int i, int j);

这篇关于Arraylist 交换元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆