ArrayList的交换元素 [英] Arraylist swap elements

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

问题描述

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

  int类型的值= [0];
    INT N = values​​.length;
    值[0] =值[N-1];
    值[N-1] =一个;

因此​​,对于一个的ArrayList<弦乐> 它会是这样

 字符串A = words.get(0);
    INT N = words.size();
    words.get(0)= words.get(N-1);
    words.get(N-1)=一


解决方案

您可以使用 Col​​lections.swap(列表<>列表中,诠释我,诠释J);

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;

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

解决方案

You can use Collections.swap(List<?> list, int i, int j);

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

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