【问题标题】:This method should invert the numbers in the ArrayList [duplicate]此方法应反转 ArrayList 中的数字 [重复]
【发布时间】:2019-04-25 06:19:37
【问题描述】:
import java.util.*;

public class Metodo {

    public static void main(String[] args) {
        ArrayList<Integer> a = new ArrayList();
        a.add(1);
        a.add(2);
        a.add(3);
        a.add(4);
        a.add(5);
        Metodo.inverte(a);
        for(int i=0; i<a.size(); i++) {
            System.out.println(a.get(i));
        }
    }

    public static void inverte(ArrayList<Integer> a) {
        ArrayList<Integer> other = new ArrayList();
        other = a;
        for(int i=0; i<a.size(); i++) {
            a.set(i, other.get(other.size()-i-1));
        }
    }
}

此方法应反转 ArrayList 中的数字,因此应打印“5 4 3 2 1”,但改为打印“5 4 3 4 5”。为什么?

【问题讨论】:

    标签: java


    【解决方案1】:
    other = a;
    

    不会创建原始List 的副本。

    aother 都引用同一个List 对象,所以当你调用a.set(0,other.get(other.size()-1) 时,你会丢失other.get(0) 的原始值。

    你应该使用:

    ArrayList<Integer> other = new ArrayList<>(a);
    

    创建原始List 的副本并删除other = a;

    【讨论】:

      【解决方案2】:

      Eran 已经回答了这个问题,但在这里做一个简单的说明。您可以使用以下方法反转 ArrayList:

      Collections.reverse(arrayList)
      

      【讨论】:

        【解决方案3】:

        您可以将a的项目以相反的顺序return的结果添加到other中:

        public static ArrayList<Integer> inverte(ArrayList<Integer> a) {
            ArrayList<Integer> other = new ArrayList<>();
            for(int i = a.size() - 1; i >=0 ; i--) {
                other.add(a.get(i));
            }
            return other;
        }
        

        所以你这样做:

        a = Metodo.inverte(a);
        

        【讨论】:

          【解决方案4】:

          正如您在回答中看到的那样,您可以了解有关您的编程语言的两件事:

          1. 副本和参考有什么区别?查看@Eran 的回答

            如果你在循环的时候改变了列表中项目的顺序,你会遇到问题。

          2. 标准库和内置类型如何帮助您?查看@Mahmoud Hanafy 的回答

            您需要花时间了解该语言及其生态系统可以为您提供什么。例如,了解reverse 集合是非常常见的事情非常重要,并且在每一个新行中你都必须问你:其他开发人员如何处理这个问题。

          【讨论】:

            猜你喜欢
            • 2017-11-08
            • 2023-03-16
            • 1970-01-01
            • 2017-04-10
            • 1970-01-01
            • 2018-09-26
            • 1970-01-01
            • 2012-11-07
            • 2013-05-13
            相关资源
            最近更新 更多