简体   繁体   English

为什么即使我只更改方法中的ArrayList而不更改原始ArrayList,我的原始arraylist仍要修改

[英]Why is my original arraylist amended even though I only make changes to my ArrayList within the method without changing the orignal ArrayList

import java.util.ArrayList;

public class BubbleSort {

  // the sort method takes in an ArrayList of Strings, sorts 
  // them in ascending number of characters, and returns a new
  // ArrayList of Strings which is already sorted. This method 
  // does NOT modify the original ArrayList passed in.

  public ArrayList<String> sort(ArrayList<String> a){
    ArrayList<String> sortingList = new ArrayList<String>();
    sortingList = a;
    String test = "";
    String test2 = "";
    int length = 0;
    int length2 = 0;
    for(int j =0; j<a.size(); j++){
        for (int i =0; i<sortingList.size()-1; i++){
            test = a.get(i);
            test2 = a.get(i+1);
            length = test.length();
            length2 = test2.length();
            if(length2<length){
                sortingList.set(i,test2);
                sortingList.set(i+1,test);
            }
        }
    }
    return sortingList;
 }
}

=================================MAIN METHOD===================================== ================================主要方法=============== ======================

import java.util.ArrayList;
import java.util.Scanner;

public class BubbleSortTest {

  public static void main(String[] args) {
    ArrayList<String> inputs = new ArrayList<String>();

    // get inputs from user
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter number of Strings to enter: ");
    int no = sc.nextInt();
    sc.nextLine(); // clears buffer in Scanner

    for (int i = 0; i < no; i++){
      System.out.print("Enter String number " + i + ": ");
      inputs.add(sc.nextLine());  // add input into ArrayList
    }

    // invoke the sort method to see if it works
    BubbleSort bs = new BubbleSort();
    ArrayList<String> sortedInputs = bs.sort(inputs);

    // print out the Strings in sortedInputs
    System.out.println("Sorted sequence:");
    for (int i = 0; i < sortedInputs.size(); i++){
      System.out.println(sortedInputs.get(i));
    }

    // print out the Strings in the original inputs
    System.out.println("Original sequence:");
    for (int i = 0; i < inputs.size(); i++){
      System.out.println(inputs.get(i));
    }
  }
}

input example 输入范例

121234256464534 121234256464534

1123123 1123123

123141243124124 123141243124124

123 123

my sorting sequence & original sequence are both amended in ascending sequence 我的排序顺序和原始顺序都按升序进行了修改 在此处输入图片说明 even though I created a new arraylist to return while ensuring I did not make any changes to the original one. 即使我创建了一个新的arraylist来返回,同时确保我没有对原始arraylist进行任何更改。

Thanks in advance 提前致谢

sortingList = a;

Both references, sortingList and a are pointing to the same ArrayList object 这两个引用sortingList和a都指向同一个ArrayList对象

Check this question to see how to see how to clone the list: How to clone ArrayList and also clone its contents? 检查此问题以查看如何克隆列表: 如何克隆ArrayList并克隆其内容?

Just remove this line from your code, 只需从代码中删除此行,

   ArrayList<String> sortingList = new ArrayList<String>();
    sortingList = a; //REMOVE THIS LINE

As you are assigning a new arraylist object just before but in the next line you are storing the reference to original object in sortingList object. 在刚好在下一行之前分配新的arraylist对象时, 会将对原始对象的引用存储在sortingList对象中。

If you want to copy all the elements to sortingList then look at Evans Post but in your example you do not need it as you are assigning the test and test2 variables from original Array supplied. 如果要将所有元素复制到sortingList,请查看Evans Post,但在您的示例中,由于从提供的原始Array分配testtest2变量,因此不需要。

As Axel pointed, use: 正如Axel所指出的,请使用:

ArrayList<String> sortingList = new ArrayList<String>(a);

With that change, in your BubbleSort class, you are still referencing strings from "a" array, hence they are not being sorted properly. 进行此更改后,在BubbleSort类中,您仍将引用“ a”数组中的字符串,因此未正确对其进行排序。 To fix, change: 要修复,请更改:

test = a.get(i);
test2 = a.get(i+1);

to

test = sortingList.get(i);
test2 = sortingList.get(i+1);

Full code: 完整代码:

public ArrayList<String> sort(ArrayList<String> a){

    //As Axel pointed, use:
    ArrayList<String> sortingList = new ArrayList<String>(a);

    String test = "";
    String test2 = "";
    int length = 0;
    int length2 = 0;

    for(int j =0; j<sortingList.size(); j++){
        for (int i =0; i<sortingList.size()-1; i++){

            //reference "sortingList" array instead of "a" array
            test = sortingList.get(i);
            test2 = sortingList.get(i+1);

            length = test.length();
            length2 = test2.length();

            if(length2<length){
                sortingList.set(i,test2);
                sortingList.set(i+1,test);
            }
        }
    }
    return sortingList;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么即使 Firebase 数据快照包含子项,我的 ArrayList 也是空的 - why is my ArrayList empty even though firebase datasnapshot contains children 我的 arraylist 尺寸为零,即使我已经向其中添加了项目 - My arraylist size is a zero even though I've added items to the it 为什么我的方法没有清除ArrayList? - Why is my method not clearing the ArrayList? 当我尝试添加ArrayList元素时,即使它是新的,为什么我的程序仍然存在? - Why does my program say the ArrayList element exists when I try to add it even though it's new? 为什么我的方法只返回存在于我的 ArrayList 中的重复项之一? - Why is my method only returning one of the duplicates that exist in my ArrayList? 如果我在复制的 ArrayList 中更改某些内容,则会更改原始 ArrayList 值。 即使我使用了列表<employee> empCopy=new ArrayList(原始列表)</employee> - Original ArrayList values Changed if i change something in Copied ArrayList. Even though i used List<Employee> empCopy=new ArrayList(origialList) 为什么我的ArrayList为空? - Why is my ArrayList Empty? 为什么我的方法没有清空ArrayList <Card> ? - Why is my method not emptying the ArrayList<Card>? 为什么我的数组列表只填充了一个元素? - Why is my arraylist only filled with one element? 为什么我的 Java 设置 arraylist 的方法不起作用? - Why is my Java Set method for arraylist not working?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM