Problem with Assigning an Array to Other Array in Java

Problem with assigning an array to other array in Java

The following statement makes val2 refer to the same array as val1:

int[] val2 = val1;

If you want to make a copy, you could use val1.clone() or Arrays.copyOf():

int[] val2 = Arrays.copyOf(val1, val1.length);

Objects (including instances of collection classes, String, Integer etc) work in a similar manner, in that assigning one variable to another simply copies the reference, making both variables refer to the same object. If the object in question is mutable, then subsequent modifications made to its contents via one of the variables will also be visible through the other.

Primitive types (int, double etc) behave differently: there are no references involved and assignment makes a copy of the value.

What happens when you assign an array to another array in java?

Both newData and data are references of the the object you created, they are located in the stack memory, according the way how works the garbage collector each reference will be removed when the execution path get the end of the scope, after the two references are removed the garbage goes to the heap in order to look object wich have no reference then tha object will be removed.

Assigning two arrays equal to each other problems

int[] x = {1, 2, 3, 4};

{1, 2, 3, 4} is allocated as an array. A reference to it is assigned to x.

int[] y ;
y = x;

A reference to that same array is assigned to y as well.

x[1] = 11;

The array that both x and y refer to is now {1, 11, 3, 4}.

x = new int[2];

A new array is allocated, due to Java semantics, as {0, 0}. A reference to it is assigned to x. Now x and y refer to two different arrays. There is no resizing being done.

x[0]=99;

The array referred to by x is changed, and now contains {99, 0}. This has nothing to do with the array y refers to, which is still happily {1, 11, 3, 4}.

How do I assign specific elements from one array into another array?

You can do this by setting array2 to be the same size as array1, that way in the best case, everything from array1 will be contained in array2.

int[] array1 = {1,2,3,4,5};
int[] array2 = new int[array1.length];

int j = 0;

for (int value : array1) {
if (approved(value)) {
array2[j++] = value;
}
}

This can be bad if the arrays are large enough and very few elements of array1 actually meet your criterion. In that case, it will be better to have the memory grow as needed to fit the elements. You can use an ArrayList for this:

List<Integer> array2 = new ArrayList<>();
for (int value : array1) {
if (approved(value)) {
array2.add(value);
}
}

Is it bad practice to assign a new array to an existing array to 'clear' the array in Java?

It is bad practice.

Firstly, assigning a new array to the variable doesn’t actually “clear” anything out (more on this below).

This is best practice:

objArray = null;

which makes the original array unreachable and therefore it will be (eventually) garbage collected.

It also avoids an unnecessary allocation of memory creating the empty array you used to replace the old one.

However, neither option “clears” out the original array, which may pose an, albeit small, security exposure. Until garbage collected, the contents of the array may be divinable if the memory contents are dumped etc.

The truly clear the array:

Arrays.fill(objArray, null);

Array assignment and reference in Java

Don't be irritated by the name 'list'. The images are taken from a python visualization, but the principle is the same in Java

Array a is assigned with a new array:

Assigning a

Array b is assigned to the instance behind a:

Assigning b

Array c is assigned with a new array:

Assigning c

And finally a is assigned to the instance behind c, b was not re-assigned and still keeps a reference to the old a:

Re-Assigning a

Images taken from a visualization on pythontutor.com

Assigning final array to an array in java

You have to strictly differentiate instances/objects from variables. final in Java is a concept that only applies to variables.

In your code you have two different variables that both refer to the same array instance. One of the variables is final, that neither affects the array nor the other variable at all.

final disallows re-assignment of the variable, it does not disallow altering the array. finalArr[1] = 4; is perfectly valid.

To illustrate this, consider

arr ---------|
|----> instance created by new int[8]
finalArr ----|

You see two different arrays, both point to the same instance. final makes sure that you can not change the arrow going out of finalArr anymore. So it will always point to that array instance. But it does not give any restrictions regarding what you do to the array instance itself or to arr.


If you are coming from a C/C++ context, final is very different to const in that regard.

Assigning an array reference to another array in Java

The second expression features an assignment expression inside an array indexer expression. The expression evaluates as follows:

  • The target of the indexer expression is selected. That's the original array a
  • The index expression is evaluated by first assigning b to a, and then taking the element of b at index zero
  • The index of the outer indexer is evaluated as b[0]
  • The index is applied to a, returning 5
  • The assignment of b to a takes effect. Subsequent accesses to a[i] will reference b, not the original a.

Essentially, your single-line expression is equivalent to this two-line snippet:

System.out.println("a[(a=b)[0]] = "+a[b[0]]); // Array reference completes first
a=b; // Array assignment is completed last

How will I assign array elements reversely into another array? I am a beginner

You can do that in many different ways, as you tried, just get and assign the element by reverse order, like below:

int[] a = {1, 2, 3, 4, 5};
int[] aR = new int[a.length];
int index = 0;
for (int i=a.length-1; i >=0; i--) {
aR[index] = a[i];
index++;
}
System.out.println(Arrays.toString(aR));


Related Topics



Leave a reply



Submit