Copy array variable to another array variable - java

I'd like to copy an array variable from one array to the array variable of another array. How would I do that? Is it just Array1[1] = Array2[1] ?

If you write
array1[1] = array2[1];
that will copy the value of the second element of array2 into the second element of array1. If that's all you wanted to do, that's fine.
It won't associate the two arrays together. If you then write:
array2[1] = someNewValue();
then that change won't be visible in array1.

Its simple...
array1[1] = array2[1];
But mind that these 2 are two different Array Object on the heap, change in one won't reflected in other.

Related

Clearing array reference in java

I have created a values[] array which consist of integers. Then, I have copied the array reference to scores[]. After some operations, how can I remove the reference from scores[] so that I can only access my array with values[]?int[] scores = {3, 5, 8};
int[] values = scores;
I believe the question you are asking is given two variables that each point to the same array (scores and values), how do you make it such that values is the only variable pointing to the array? You simply need to assign a different value to scores. I don't know if you care what the value of scores is after this operation is completed, but one thing you could do is:
scores = <Literally anything except "scores" (eg. null)>;
This will cause the variable scores to no longer point at the same array. If you want to maintain the value of scores while deleting the pointer to the array, the way to do this is to copy scores into itself.
scores = Arrays.copyOf(scores, scores.length);

How to calculate the number of elements in multidimentional arrays?

i've had this question ever since i learned two dimensional arrays... and i hope someone can clarify things for me..
here's what i know
int[] x= new int[2];
this one dimensional array has two elements.
int[][] y=new int[2][3];
this two dimensional array has six elements right? (2 x 3 = 6)
but when i look into the way a two dimensional array is actually made,
first a reference type variable named y that can store memory
addresses of a two-dimensional array is made in the stack.
then an object with two elements that can store one dimensional
memory addresses is made in the heap.
then another 2 one-dimensional arrays are made, each consisting 3
elements that can store int type values. and the memory addresses of
these two one dimensional arrays are assigned to the two elements
that were made earlier inside the object.
then this object's memory address is assigned to the y variable that
is in the stack.
now the problem i have is, only two elements are made inside that object in the beginning right? so doesn't that mean that the two dimensional array has two elements. and the two one-d arrays have 3 elements each?
all of these questions bugs me because y.length = 2 and y[0].length =3
please correct me if i am wrong and hope someone could help me. thanks
Yes, you're absolutely right. Java doesn't have 2-dimensional arrays per se. All it has is arrays containing arrays, and syntax sugar (new int[2][3]) to create them.
But you could indeed have an array containing arrays of different lengths:
int[][] array = new int[2][];
array[0] = new int[5];
array[1] = new int[3];
System.out.println(Arrays.deepToString(array));
// prints [[0, 0, 0, 0, 0], [0, 0, 0]]
So it you get an int[][] and want to know how many integers it contains, you need to loop through the outer array and sum the lengths of the inner arrays. Unless you have the guarantee that all inner arrays have the same length. In that case, you can multiply the length of the outer array by the length of any of the inner arrays.
In Java, multidimensional arrays are actually arrays of arrays. For example, a two dimensional array variable called arr looks like:
int arr[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to arr. Conceptually, this array will look like the one shown in the Figure:
When you allocate memory for a multidimensional array, you need only specify the
memory for the first (leftmost) dimension. You can allocate the remaining dimensions separately. For example:
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
While there is no advantage to individually allocating the second dimension arrays in this situation, there may be some benefits. Like allocating dimensions manually, you do not need to allocate the same number of elements for each dimension. As stated earlier, since multidimensional arrays are actually arrays of arrays, the length of each array is under your control.
You could flatten your multidimensional Array with this method, and call List#size() on it.
It will even flatten nested Lists, Sets, Maps and Queues.

Java arrays value setting

How do I add an array value to another array while increasing the array value of the other array each time. For example, if I want array1 value to be added to array2 and when I search for the array2[position] it appears as the value of array1.
array1[position]=array2[count]
I kind of want it so that it is looped but I don't know how
From your comment -> Its going to get clumsy if you insist on arrays - using ArrayList will be much easier:
ArrayList<Item> cart = new ArrayList<>();
cart.add(array1[position]);
If you insist on using arrays you must create a new array with larger size and copy the old array into the new array each time you run out of space - actually this is what ArrayList does for your (albeit in a clever way - increasing size by 50% each time it runs out of space)

Define the number of elements of a one-dimensional array based on a variable rather than a constant

I am little confused at to what based on a variable means. I made an attempt at it not sure if its correct. Is it?
int size;
System.out.print("Enter the array size: ");
size = input.nextInt();
int[] arr = new int[size];
Define the number of elements of a one-dimensional array based on a
variable rather than a constant
You have done it right. lets break up it into parts to clear your confusion.
Define the number of elements of a one-dimensional array
int size;
System.out.print(“Enter the array size: “);
size = input.nextInt();
here you have defined how many elements should be in you array. In simple words size of array.
based on a variable rather than a constant
you have taken above variable size to define the size of length , it is variable means it can have any value which user enters not hard coded in the code.
Hope your confusion is clear.
Well tried mate.
I think it is not the problem of variable or constant, it is about the confusion of usingnew int[size].
In fact, it is just a second format ofnew int[](size), it will new an object which is an array type. And int is just a generic parameter.

Copying Arrays The Right Way

I came across 2 examples from my notes which is about copying arrays.
The first example given below, stated that it is not the way to copy an array. But, when i tried to run the code, it managed to copy all the values from array1 to array2.
int []array1={2,4,6,8,10};
int []array2=array1;
for(int x:array2){
System.out.println(x);
}
The second example given, was saying the right way to copy an array.
int[] firstArray = {5, 10, 15, 20, 25 };
int[] secondArray = new int[5];
for (int i = 0; i < firstArray.length; i++)
secondArray[i] = firstArray[i];
My question is, are these 2 examples appropriate to be applied in coding or Example 2 is preferred. If you were my lecturer, I were to apply Example 1.. I will be given less mark compared to Example 2 method or just the same?
The first example doesn't copy anything. It assigns a reference of the original array to a new variable (array2), so both variables (array1 and array2) refer to the same array object.
The second example actually creates a second array and copies the contents of the original array to it.
There are other easier ways of copying arrays. You can use Arrays.copyOf or System.arraycopy instead of explicitly copying the elements of the array via a for loop.
int[] secondArray = Arrays.copyOf (firstArray, firstArray.length);
or
int[] secondArray = new int[firstArray.length];
System.arraycopy(firstArray, 0, secondArray, 0, firstArray.length);
Perfect way to copy elements is
System.arraycopy(array1,0, array2, 0, array1.length);
That above code is replacement for you second example which avoids a for loop.
And where in your first example, you are just referring the first array. So what ever changes happened to the first array can be seen from second array.
My question is, are these 2 examples appropriate to be applied in coding or Example 2 is preferred.
See again, they are not doing the something to compare. First one pointing to array reference and second snippet of code referencing elements it it. So you just can't compare them.
And there are other ways to copy array elements as well just like others mentioned and I prefer System.arraycopy because
1)Arrays.copyOf creates another array object internally and returns it where as System.arraycopy uses the passed array.
2) Clone is the too slow. Never use it unless you have no other choice.
There are few reasons I'm avoid clone. Here is
Josh Bloch analysis on clone vs copy constructor (when you clone individual elements).
To demonstrate the problem with the first method, try this:
int[] array1 = {2, 4, 6, 8, 10};
int[] array2 = array1;
array1[0] = 0;
System.out.println(array2[0]);
What do you think this will print?
0
It will print 0, because array2 now points to array1:
both variables now refer to the same object,
so modifying the content of any one of these will appear to modify both.
So your first method is NOT called copying an array.
It's a simple assignment, from one variable to another,
in this case assigning the value of array1 to array2,
so that both variables point to the same thing.
As for your second method,
here's a much simpler way to accomplish the same thing:
int[] array2 = array1.clone();
In your first example, you end up with only one array with two variables referring to it. Assignment only passes a reference to the array. So both firstArray and secondArray are pointing to the same array. It's not a copy. Try to set firstArray[0] = 99 and print secondArray and you'll see it's the same array.
In the second example, it's an actual copy - you have created a new array and copied each value. Now, assigning firstArray[0] = 99 won't change the array referred to by secondArray because it's a copy.
So the answer is: if you give the first way, you'll get lower marks.
In real use, there are better ways to copy arrays, using System.arraycopy, Arrays.copyOf or firstArray.clone().
int[] secondArray = new int[5];
In the second example, you are creating an array of int using new operator and copying the elements to it manually using for loop. Whenever you use new operator in java, a new memory allocation happens (object creation).
Where as in the first, it is just reference assignment, both are pointing to same array. You can easily verify that by changing the content of one array see the same effect into the second array. This will not happen in the second array copying.
int []array2=array1;

Categories