How can I copy an array by value in Java? [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Make copy of array Java
I'm a beginner at Java and I need to copy the contents of one array into another variable. However, Java always passes the array by reference instead of by value.
Here's what I mean if that was confusing:
int test[]={1,2,3,4};
int test2[];
test2=test;
test2[2]=8;
for(int i=0;i<test2.length;i++)
System.out.print(test[i]); // Prints 1284 instead of 1234
In this example, I don't want the value of test to change. Is this possible without using any of the more advanced features of Java such as ArrayList and Vectors?
Edit: I tried System.ArrayCopy and test.clone(), but they still don't seem to work.
Here's my actual code:
temp_image=image.clone();
for(int a=0;a<image.length;a++)
for(int b=0;b<image[0].length;b++)
image[a][b]=temp_image[image.length-1-a][b];
Basically I'm trying to flip the "image" upside down. Is there an error somewhere in the code?

You need to clone your array.
test2=test.clone();

Starting in Java 6 you can use Arrays.copyOf:
test2 = Arrays.copyOf(test, test.length);
For what you're looking to do, test.clone() is fine. But if you wanted to do a resize, copyOf allows you to do that. I think in terms of performance it
System.arraycopy would give even more options if you needed them.

Because test and test2 are both pointers to the same array, you are changing the value of both test and test2 with your statement test2[2]=8
A solution would be to copy the contents of test into test 2 and change the value at the specific index of test2.
for (int i=0,i<test.length,i++)
test2[i]=test[i]
//Now both arrays have the same values
test2[2]=8
for (int j=0,j<test.length,j++)
System.out.print(test[i])
System.out.println()
System.out.print(test2[i])
Will output
1 2 3 4
1 2 8 4

Related

Why does the output for while (arar==arr){ arr[0]=2; } display this ([I#60e53b93)? [duplicate]

This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 1 year ago.
I basically see this in the output screen every time I am trying to set two non-boolean types equal to each other using a binary operator.
What I do not understand is, if the compiler goes on and compiles it but displays [I#60e53b93 (which seems to me to be an address),
is it because it is using arr as an object or is it because it is actually working and the loop is running infinitely?
So what I was trying to do was just experiment with arrays and see what I could do with them because it's been a while since I worked with Java.
So what I basically did was:
int [] arr = {1,2,3,4,5,6};
int[]arar={1,2,3,4,5,6};
while (arar==arr){
arr[0]=2;
}
System.out.println(arr);
and so I was basically expecting a red flag but then the code ran and displayed [I#60e53b93 which I did not understand why?
Can somebody explain this to me and if possible how I can display the array arr even if it is in a continuous loop?
Two things are going on here:
arr will never equal arar because == uses reference equality; since arr and arar can be modified independently, they aren't the same object.
System.out.println(anyArray) will always display output like yours, because arrays don't have a useful toString function.
You can solve both problems by using static methods from Arrays:
while (Arrays.equals(arr, arar)) {
...
}
System.out.println(Arrays.toString(arr));
Because arr is just a reference to an array. It's not the content of the array. The reference holds the memory location where the actual content of the array is. Calling toString() on an Object will by default output its memory location. (toString() will implicitly be called by System.out.println)
Every object in Java has a toString() method. Though you can call System.out.println basically on everything. Some objects have a custom toString implementation and print something useful, and others (like arrays) just print their memory location.
If you want to display the array contents, you have to loop over the array:
for(int elem : arr) {
System.out.println(elem);
}

Java changes the variable without me doing so [duplicate]

This question already has answers here:
How to copy Java Collections list
(18 answers)
How do I clone a generic List in Java?
(14 answers)
Closed 2 years ago.
So I wanna compute a covexhull but in the I want the right and left sets seperately. I cannot understand what Java is doint right here exactly.
So I first call the hullset function for the right part and then put it in rightCov (at that point right set has 3 points). After that I can hullset for the left set . The problem is that even though I have "saved" the 3 points of the right set after the second call of the hullset,for the left set only,the variable rightCov takes all the 5 points of the covexhull without me using it again. The calls are below.
hullset(A, B, rightSet, covexHull);
ArrayList<Point> rightCov=covexHull;
hullset(A,B,leftSet, covexHull);
ArrayList<Point> rightCov=covexHull; assigns rightCov the same reference as covexHull so they both point to the same list in memory. You should use addAll methos to copy the elements from one array into another.

Array Length in Java - Performance [duplicate]

This question already has answers here:
What is the Cost of Calling array.length
(8 answers)
Java native array lengths
(6 answers)
Closed 9 years ago.
Let's say I create an array of ints with length 10, i.e.
int[] array = new int[10];
At some point in my code, I want to compare the value of an int variable, let's call it var, with the length of the array.
I would like to know if this piece of code:
if(var == array.length) { // stuff }
and this piece of code:
if(var == 10) { // stuff }
which do exactly the same thing, have also the same performance.
In other words, I would like to know the internal mechanics that the JVM (?) uses to find the length of the array (I don't say "to return" since length is a field, not a method). Does it make use of iteration? Because if it does, then the 2nd piece of code would be faster than the 1st one.
EDIT: Similar question regarding array.length cost (even though focusing more to its use in for loops):
What is the Cost of Calling array.length
.length is a property, so it would not do iteration for sure. Still, the value of the property is, naturally, fetched at runtime, meaning that the second solution will be a little bit faster (as this is comparison with constant).
Still the first implementation is far more preferable:
This makes your code quite more maintainable
You can alter the length of the array only at one place
You will never feel the performance difference unless you pass through this if litterally millions of times in a second.
EDIT By the way you can yourself tell this is a property - there are no braces after the call. I at least do not know of a way in java to make property access do additional computation, but just retrieving its value.
.length is a property of the array, not a function. Thus, the result would be available immediately, with no iteration necessary.
From the Java Doc
The members of an array type are all of the following:
The public final field length, which contains the number of components
of the array. length may be positive or zero.
length is an final field of array, so no iterations are required while writing following code.
if(var == array.length) { // stuff }
And it is good coding practice indeed.
The length property of an array is extracted in constant (O(1)) time - there is no iteration needed. It's also good practice to use this.

Is there a method in Java that lets you find the index of an element in an int array? [duplicate]

This question already has answers here:
Where is Java's Array indexOf?
(13 answers)
Closed 9 years ago.
I need to assess the last int in an array where a certain conditional is met. My program can work out what that int is, but it needs to also know where it's position was in the array. I searched on stack-exchange and someone posted this:
Arrays.asList(array).indexOf(indexPos);
As a possible solution, but I am not sure if I am doing it right, because I get the error
cannot find symbol. I also allowed:
int test = Arrays.asList(array).indexOf(indexPos);
And then tried to print test, but I could not even get to that point. Thanks.
You may need to import java.util.Arrays to get the symbol.
There is no guaranteed way of finding the position of an element in an array except for looping over the array - that is basically what your asList snippets are doing.
This will work as long as your arrays don't have duplicate values. If you need to handle duplicate values, you may need to rethink you data structs.
Someone posted a similar question that someone else asked. It seems that this has worked for me.
The Code is:
java.util.Arrays.asList(seq).indexOf(indexPos);
and the Question:Where is Java's Array indexOf?
Yes you have the method defined in List interface. So you need to use asList() function followed by indexOf() function.
If the array is not sorted you can use java.util.Arrays.asList(theArray).indexOf(o)
If the array is sorted, you can make use of a binary search function(improves performance) java.util.Arrays.binarySearch(theArray, o)
As for the error make sure you have imported java.util.Arrays. Also that you have defined Array seq and int indexPos which makes your code int test = Arrays.asList(seq).indexOf(indexPos);.

Initializing a 2D-array with zero in JAVA [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Any shortcut to initialize all array elements to zero?
How to Initializing a normal 2D array with zeros(all shells should have zero stored) without using that old looping method that takes lots of time .My code wants something that should take very less time but via looping method my time limit exceeds.
The important thing to realise here is that if you're storing primitives then the default value is zero (scroll down to the Default Values section). This applies to array initialisation as well as simple variable initialisation, and consequently you don't have to initialise the array contents explicitly to zero.
If you have to reset an existing structure, however, then you'd have to loop through the structure, and you may be better off initialising a new instance of your array structure.
Note that if you're creating an array or arrays, obviously you have to initialise the first array with the contained array.

Categories