This discussion is archived
5 Replies Latest reply: May 9, 2007 9:21 PM by 807599 RSS

Newbie Array Question

807599 Newbie
Currently Being Moderated
I am sure this has been asked before, but can anyone tell me why this code creates two identical arrays.
int[] test = {1, 2, 3};
int[] tempTest = test;

test[0] =5;

test = tempTest;
Now, I would think that test would return to its initial value because it is stored in tempTest but that is not the case both arrays are containing the new value of 5 in position 0.
  • 1. Re: Newbie Array Question
    807599 Newbie
    Currently Being Moderated
    temp and tempTest are variables not arrays. They store references (or pointers) to the same array. Therefore there is only only array so any changes you make is reflected by the two variables because they both refer to the same array.
  • 2. Re: Newbie Array Question
    807599 Newbie
    Currently Being Moderated
    You should also try changing a value in one of the positions of the second array. Are the changes reflected again?
  • 3. Re: Newbie Array Question
    807599 Newbie
    Currently Being Moderated
    Yep, if I change a value in the second array it is reflected in the first. I figured it had to do with them being just pointers. Thanks for the help. I guess one more question to add to this would be is there any way to set them equal with a one line command, or is the only way a type of loop to set each positions equal.

    Message was edited by:
    StackFlow
  • 4. Object assignment
    807599 Newbie
    Currently Being Moderated
    Read a basic tutorial of java,

    When you assign a reference of object to other variable of type object, you are actually assigning a reference, it will neither create a new object nor copy existing object, both variable will point to same object,

    ex

    Car c1 = new Car();
    Cac c2 ;
    c2 = c1; // both c1 and c2 referes to same inmemory representation of car
    //object

    //if you make any change in c2, tht changes will be reflected on c1 also, coz both referes to same object

    if (c1 == c2) {
    System.out.println ("both are same");
    }
    else {
    System.out.println ("Different");
    }

    sudhir
    http://www.jyog.com
  • 5. Re: Object assignment
    807599 Newbie
    Currently Being Moderated
    Thanks for that Sudhir but they already understood.

    Thanks also for pimping your website!