1

I have a function in which user inputs numbers and those numbers are added to an Arraylist. That list is passed to another class for process and the return value is printed out. But when the value is returned, it changes the value of the original Arraylist used to call the class.

System.out.println("NATIVE LIST : "+loN); // original value - [2,+,3]
Evaluate evaluate = new Evaluate();
if (loN.size() > 2) {
      evaluate.setR(loN);
      System.out.println(evaluate.start()); // prints 5.0
}
System.out.println(loN); // value gets changed [5.0]

code for Evaluate Class :

 public void setR(ArrayList<String> r) {
    question = r;
}

public Number start(){
    if (question.size() == 1){
        return Double.parseDouble(question.get(0));
    }else{
        test();
    }
}

private void check_pos(String c){
    if (question.contains(c)){
        pos = question.indexOf(c);
    }
}
int test(){
    try {
        String val = null;
        if (question.contains("+")) {
            check_pos("+");
            val = String.valueOf(Double.parseDouble(question.get(pos - 1)) + 
 Double.parseDouble(question.get(pos + 1)));
        }
        if (pos != question.size()-1) {
            question.set(pos - 1, val);
            question.remove(pos + 1);
            question.remove(pos);
            start();
        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return 2709;
}

1 Answers1

0

It is normal that in your case when you try to print the list again, after processing, it has changed. When you pass an object reference to a method as a parameter, it means that you can change its properties in the called method. From the moment you associate the reference of the original list with the variable "question", every time you perform an operation using the reference of "question" you modify the properties of the original object. There are two ways to solve your problem:

  1. Instead of directly associating the references in the setR method, you have to associate a new list starting from the original one. For example "question = new ArrayList (r);"

  2. Modify the structure to build a tree starting from the list. However, in this case you should change the application logic.

My advice to make the changes easier for you is to use the first solution

Marcius
  • 26
  • 3