1

I tried to run a for-loop and update a double value in a list , and I found that I failed. I search on the web and I know that when getting double value by List#get(i) method is simply get a copy of the value, such that will not update a value in a list, just like the code below.

        List<Double> list1 = new ArrayList<Double>();
        list1.add(10.0);
        for(int i = 0; i < list1.size() ; i++){
            Double value = list1.get(i);
            value = value/100;
            System.out.println(list1.get(i));
        }

        //Result 10.0

the only way is use the List#set(i, value) method.

Now I add a Test class

class Test{
    Double value;

    public Test(Double value){
        this.value = value;
    }
}

and do the similar thing with Test class

        List<Test> list2 = new ArrayList<Test>();
        Test test = new Test(10.0);
        list2.add(test1);

        for(int i = 0; i < list2.size() ; i++){
             Test test = list2.get(i);
             test.value = test.value / 100;
             System.out.println(test.value);
        }

        //Result 0.1

My question is : Why the value in a list will update. Isn't the test object in a for loop still a copy of the original one ? Is it because of primitive data type or reference difference?

2
  • 1
    Isn't the test object in a for loop still a copy of the original one? - No, what's being returned by list2.get(i) in this case is a reference to the original Test object. Commented Jul 29, 2014 at 17:44
  • you correct my wrong idea! thank you Commented Jul 29, 2014 at 17:59

2 Answers 2

3

Actually, the issue here is that the primitive wrapper types are immutable.

List<Double> list1 = new ArrayList<Double>();
list1.add(10.0);
for(int i = 0; i < list1.size() ; i++){
  Double value = list1.get(i);
  value = value/100;                      // <-- creates a new value!
  System.out.println(list1.get(i));
}

You could use the shorter,

List<Double> list1 = new ArrayList<Double>();
list1.add(10.0);
for(int i = 0; i < list1.size() ; i++){
  list1.set(i, list1.get(i) / 10);
  System.out.println(list1.get(i));
}
Sign up to request clarification or add additional context in comments.

1 Comment

great, thanks for your help, I know this method, but I totally forget the immutable and mutable thing.
2

The difference is between immutable objects (such as Float and String) and mutable objects (such as your Test class).

Mutable objects can be updated. The list contains a reference to the object. When you change the content of that object, the list still refers to the same object, which is now changed.

1 Comment

thanks for your help, you teach me the immutable and mutable concept clearly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.