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:
Array b
is assigned to the instance behind a
:
Array c
is assigned with a new array:
And finally a
is assigned to the instance behind c
, b
was not re-assigned and still keeps a reference to the old 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
toa
, and then taking the element ofb
at index zero - The index of the outer indexer is evaluated as
b[0]
- The index is applied to
a
, returning5
- The assignment of
b
toa
takes effect. Subsequent accesses toa[i]
will referenceb
, not the originala
.
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
How to Make a Deep Copy of Java Arraylist
Reserved Words as Names or Identifiers
How to Get the Session Object If I Have the Entity-Manager
Midpoint Between Two Latitude and Longitude
How to Capture a Jframe's Close Button Click Event
Access Restriction: Is Not Accessible Due to Restriction on Required Library ..\Jre\Lib\Rt.Jar
Jsoup Character Encoding Issue
How to Resize Jlabel Imageicon
Java Generics Wildcard Question: List<? Extends A>
Validation of a List of Objects in Spring
How to Check If a String Contains Only Digits in Java
Java.Util.Concurrentmodificationexception Not Thrown When Expected
Getting an Attribute Value in Xml Element
Should Getters and Setters Be Synchronized
Hibernate Validation of Collections of Primitives
What Is Better: Multiple "If" Statements or One "If" with Multiple Conditions