0

I didn't understand why I1.array[0]=555 is? I only want to change arr[0]

Intar I1 = new Intar(10);

int [] arr = I1.array;

        arr[0]=555;

public class Intar {

    int length;
    int [] array;


    public Intar(int lengt){

        length=lengt;
        array=new int[lengt];
        Random ran =new Random();

        for(int i=0; i<length; i++){

            array[i]= ran.nextInt(100);

**When I use System.out.println before and after arr[0]=555 **

I1.array [11, 57, 77, 74, 50, 62, 1, 11, 23, 27] 
arr      [11, 57, 77, 74, 50, 62, 1, 11, 23, 27] 
After arr[0]=555
I1.array [555, 57, 77, 74, 50, 62, 1, 11, 23, 27] 
arr      [555, 57, 77, 74, 50, 62, 1, 11, 23, 27]
1
  • 1
    They become the same object. Commented Mar 31, 2016 at 2:59

2 Answers 2

5

int [] arr = I1.array; does not copy the array, it just assigns the reference to the l1.array to arr. You could use Arrays.copyOf(int[], int) to make a copy like

int[] arr = Arrays.copyOf(l1.array, l1.array.length);
Sign up to request clarification or add additional context in comments.

Comments

0
Intar I1 = new Intar(10);

Creates an Intar object, using the constructor public Intar(int lengt), this then initilizes the fields of the Intar object to be an array of 10 random numbers, and a length = 10.

When you write

int [] arr = I1.array;

You are telling arr to reference the object stored in I1's field called array (the array of 10 randomly generated numbers). So when you then set arr[0]=555 you are also setting I1.array's 0th element to be 555 as well.

What you have to understand is I1.array hold a reference to the array which is stored in the Intar object. And now arr is referencing the same object as I1.array is referencing.

For example:

public class Foo {

    int val;
    public Foo(int val){
        this.val = val;
    }
    int getVal(){
        return this.val;
    }

}

Then we can do this:

public static void main(String[] args) {
    Foo a,b;

    a = new Foo(5);
    b = a;
    b.val = 5;
    System.out.println(a.getVal());
}

5 will be the output as b now references a, and we changed the value of b thus we changed the value of a.

Comments

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.