There is an example program in my java book that makes no sense to me. Basically it passes an array reference to a method. But the outcome is that the array itself is modified even though the method doesn't have a return or something within it that indicates its doing something other than creating it's own instance of the array.
public class PassArray
{
public static void main( String[] args )
{
int[] array = { 1, 2, 3, 4, 5 };
System.out.println(
"Effects of passing reference to entire array:\n" +
"The values of the original array are:" );
for ( int value : array )
System.out.printf( " %d", value );
modifyArray( array ); // pass array reference to method modifyArray
System.out.println( "\n\nThe values of the modified array are:" );
// output the value of array (why did it change?)
for ( int value : array )
System.out.printf( " %d", value );
} // end main
// multiply each element of an array by 2
public static void modifyArray( int array2[] ) // so this accepts an integer array as an arguement and assigns it to local array array[2]
{
for ( int counter = 0; counter < array2.length; counter++ )
array2[ counter ] *= 2;
} // What hapened here? We just made changes to array2[] but somehow those changes got applied to array[]??? how did that happen?
//What if I wanted to not make any changes to array, how would implement this code so that the output to screen would be the same but the value in array would not change?
} // end class PassArray
Please explain why this is the case and also how this could be implemented somehow so that the values of array are not changed. S
// What hapened here? We just made changes to array2[] but somehow those changes got applied to array[]??? how did that happen?
Because java is pass by reference value. Copy of the reference will be passed to the method. This reference also still points to original array. Any change you perform on this reference will reflect on original array.
how this could be implemented somehow so that the values of array are not changed.
One way is, create new array inside the method and assign it this reference.
Example:
public static void modifyArray( int array2[] )
{
array2 = new int[10];
//Copy only ten elements from outer array, which populates element at index 2.
for ( int counter = 0; counter < array2.length; counter++ )
array2[ counter ] *= 2;
}
Now the updates/operations you perform on this reference will effect on new array created inside the method, not on original array.
See this SO discussion for more information.
When you pass an array to a method, you're really just passing a copy of the reference to the array.
Any changes that are made to the array will be reflected in the object that was passed.
What actually gets passed to modifyArray is a copy of the array reference, which is why people say Java is "pass by reference value".
What's happening is that when you pass array to modifyArray(int[]) is that array which is actually not a java primitive, so array2 is really still the same object as array.
A fairly easy way to copy the first array would be to use System's arrayCopy method like this
public static int[] modifyArray( int array[] )
{
int length = array.length; // length of the original array
int array2[] = new int[length]; // the new array which we will copy the data into
System.arraycopy(array, 0, array2, 0, length); // now we copy the data from array[] into array2[]
for ( int counter = 0; counter < array2.length; counter++ ) {
array2[ counter ] *= 2; // multiply by 2
}
return array2; // return the array with the new values
}
You now have a copy of the original array, but with all the values multiplied by 2.
I hope this helps.
public class PassArray
{
public static void main( String[] args )
{
int[] array = { 1, 2, 3, 4, 5 };
System.out.println(
"Effects of passing reference to entire array:\n" +
"The values of the original array are:" );
for ( int value : array )
System.out.printf( " %d", value );
modifyArray( (int[])array.clone(); ); // pass array reference to method modifyArray
System.out.println( "\n\nThe values of the modified array are:" );
// output the value of array (why did it change?)
for ( int value : array )
System.out.printf( " %d", value );
} // end main
// multiply each element of an array by 2
public static void modifyArray( int array2[] ) // so this accepts an integer array as an arguement and assigns it to local array array[2]
{
for ( int counter = 0; counter < array2.length; counter++ )
array2[ counter ] *= 2;
} // What hapened here? We just made changes to array2[] but somehow those changes got applied to array[]??? how did that happen?
//What if I wanted to not make any changes to array, how would implement this code so that the output to screen would be the same but the value in array would not change?
}
Please read this link to understand better
Related
import java.util.ArrayList;
public class Paaohjelma {
public static int pienin(int[] taulukko) {
int temp, size;
size = taulukko.length;
for(int i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(taulukko[i]>taulukko[j]){
temp = taulukko[i];
taulukko[i] = taulukko[j];
taulukko[j] = temp;
}
}
}
return taulukko[0];
}
public static int pienimmanIndeksi(int[] taulukko) {
ArrayList<Integer> tauli = new ArrayList<>();
for (int i : taulukko) {
tauli.add(i);
}
return tauli.indexOf(Paaohjelma.pienin(taulukko));
}
public static int pienimmanIndeksiAlkaen(int[] taulukko, int aloitusIndeksi) {
// this methods should get the index of smallest value starting from specified index
int[] tempTauli = taulukko;
tempTauli = new int[tempTauli.length - aloitusIndeksi];
// this gets the right values to temporary array
if (aloitusIndeksi > 0) {
int index = 0;
int indexTauli = 0;
for(int value : taulukko) {
if(index >= aloitusIndeksi) {
tempTauli[indexTauli] = taulukko[index];
indexTauli++;
}
index++;
}
}
// values added are automatically sorted from smallest to largest?
// this shouldn't be, array should be 5, 99, 3, 12 but is shown as 3, 5, 12, 99
for(int inty : tempTauli) {
System.out.println(inty);
}
// get the index of smallest value in array
// index is 0 should be 2
int index = Paaohjelma.pienimmanIndeksi(tempTauli);
// return index of smallest value (add starting index to get the index of smallest value in the original array when starting from specified index)
return index+aloitusIndeksi;
}
public static void main(String[] args) {
// test code
int[] taulukko = {3, 1, 5, 99, 3, 12};
int minIndex = Paaohjelma.pienimmanIndeksi(taulukko);
System.out.println("Pienin: " + Paaohjelma.pienin(taulukko));
System.out.println("Pienimmän indeksi: " + minIndex);
System.out.println(Paaohjelma.pienimmanIndeksiAlkaen(taulukko, 2));
}
}
Hello! I'm doing some programming course work for school and have been stuck in this particular part for couple hours. So I decided it would be best for someone else to take a look and provide some light why my approach for this problem isn't working.
What should happen: class method PienimmanIndeksiAlkaen should return the index of smallest value in provided int array starting from specified index.
The main problem I have been having is that the array seems to be automatically sorting itself and I have no idea what is possible causing this. I have commented the relevant part of the code and would be more than happy if someone could explain why this is happening and what possible could be done to prevent this.
The reason your array is sorted is when you call
System.out.println("Pienin: " + Paaohjelma.pienin(taulukko));
you sort the array.
When you pass the array into this function, you aren't actually passing the value of the array, but the pointer to the array - the address of the array in memory. This is the difference between passing parameters by value or by reference.
How do you know if the value is passed by value or by reference?
As a rule of thumb:
primitive values - i.e. int, double, etc. will be passed by value - their value will be copied and passed to the function.
Any other type, namely arrays and classes, will be passed by reference - the address of the value in memory will be passed to the function, thus any change to the value inside the function will affect it when the function ends too.
Read more here
This question about a 2D array being passed into a method came up in class. Can someone explain why the original array d is unchanged after a call to doStuff() ? I debugged the code and saw that the method was reversing the values, but then when returned, the original array remained unchanged. I thought passing arrays into a method and changing values in that method would affect the original array. Here that is not the case, the original array is unchanged. My first thought was the orignal would be reversed. But no.
Initialize the array d and call doStuff as
follows:
int d[][] = { {-1,0,1},
{5,6,7},
{2,3,4} };
doStuff(d);
public static void doStuff (int [][] frst)
{
int len = frst.length;
int sec[][] = new int[len] [];
for (int j=0; j<len; j++)
{
sec[j] = frst[len –j -1];
}
frst = sec;
}
You already have some good answers, but here's a bit of code showing the two cases that may seem to be inconsistent, but are indeed explained by the fact that java is pass-by-value. The tricky bit is that in the case of arrays, it's the reference to the array that's being passed by value, not the array itself.
Hence the called function receives a copy of the reference to the same array as the caller function, and can modify elements within that array. But when the called function modifies the reference itself to refer to a different array it is modifying a copy, which has no effect on the caller --- that is, in the caller environment the variable is still referring to the original array.
This is easier to explain with boxes and arrows :-), but hopefully the code and output below will be helpful:
$ cat PBV.java
class PBV
{
private static void modfiyArrayElement(int[] intArray) {
// intArray is referring to the same array as in main
intArray[0] = 17;
}
public static void main(String[] args) {
int[] a = new int[]{ 1, 2, 3 };
System.out.println(a[0]);
modifyArrayElement(a);
System.out.println(a[0]);
}
}
$ java PBV
1
17
$ cat PBV2.java
class PBV2
{
private static void modfiyArrayReference(int[] intArray) {
System.out.println("\nIn modifyArrayReference:");
System.out.println("intArray[0] is " + intArray[0]);
System.out.println("ref value of intArray is: " + intArray);
intArray = new int[] { 100, 200, 300 };
// intArray is no longer referring to the same array as in main!
// at this point munging with intArray won't have an effect in main
System.out.println("\nintArray[0] is now " + intArray[0]);
System.out.println("ref value of intArray is: " + intArray +"\n");
}
public static void main(String[] args) {
System.out.println("in main:");
int[] a = new int[]{ 1, 2, 3 };
System.out.println("a[0] is " + a[0]);
System.out.println("ref value of a is: " + a);
modfiyArrayReference(a);
System.out.println("back in main:");
System.out.println("a[0] is still " + a[0]);
System.out.println("ref value of a is still: " + a);
}
}
$ java PBV2
in main:
a[0] is 1
ref value of a is: [I#55a6c368
In modifyArrayReference:
intArray[0] is 1
ref value of intArray is: [I#55a6c368
intArray[0] is now 100
ref value of intArray is: [I#37670cc6
back in main:
a[0] is still 1
ref value of a is still: [I#55a6c368
Java is pass by value
Return your value and set it to your value.
int d[][] = { {-1,0,1},
{5,6,7},
{2,3,4} };
d = doStuff(d);
public static int[][] doStuff (int [][] frst)
{
int len = frst.length;
int sec[][] = new int[len] [];
for(int j=0; j<len; j++)
sec[j] = frst[len-j-1];
return sec;
}
}
You can also set the value of the passed array directly (array variables are a reference to an array, so editing the elements of your passed array reference will work:
public static void doStuff (int [][] frst)
{
int len = frst.length;
int sec[][] = new int[len] [];
for(int j=0; j<len; j++)
sec[j] = frst[len-j-1];
for(int j=0; j<frst.length;j++)
frst[j] = sec[j]
}
Here what happens.
There are 2 arrays created, the initial one and the second, created inside the doStuff method.
There are 3 references (variables) to the arrays in the code:
external (for the method): d
internal: first and sec.
Inside the doStuff method the second array is indeed populated as the reverse of the initial which is not changed at all.
At the end of the doStuff method both first and sec reference the same object, the second one, and not the original - hence the behavior you see
I'm trying to merge 2 int arrays using this custom function I found on Google:
public static <T> T[] arrayMerge(T[]... arrays)
{
int count = 0;
for (T[] array : arrays) count += array.length;
T[] mergedArray = (T[]) Array.newInstance(arrays[0][0].getClass(),count);
int start = 0;
for (T[] array : arrays) {
System.arraycopy(array, 0, mergedArray, start, array.length);
start += array.length;
}
return (T[]) mergedArray;
}
but I'm fail to understand what parameters this function takes. I was hoping it would work like arrayMerge(int[], int[]), but Eclipse tells me it doesn't take these arguments.
I can't Google a capital T to find an answer.
You can answer in a form or reading material, but an example of using this function to merge 2 int arrays would be nice (does it eliminate duplicates, if not, how can I also achieve that?).
The method takes any number of arrays, all having the same type:
String[] array1 = ... ;
String[] array2 = ... ;
String[] array3 = ... ;
String[] mergedArray = ArrayHelper.arrayMerge(array1, array2, array3);
However, due the way generics work in Java, you cannot pass an array of a primitive type (such as int[]).
The code you have post here is for any type of array not only int and for more than 2 arrays to merge. (unlimited)
T stand for a generic Type. see Generics in Java.
You can use only the System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
src the source array.
srcPos starting position in the source array.
dest the destination array.
destPos starting position in the destination data.
length the number of array elements to be copied.
First make an array which has the length of both arrays.
public merge(int[] x, int[] y) {
int[] merged = new int[x.length + y.length]
Than copy with System.arraycopy the first array x into merged at 0.
And copy with System.arraycopy the 2nd array y into merged at x.length
But it doesn't eliminate duplicates.
For no duplicates you can use a Set. But we have to work with Integer not int.
So we have to convert to Integer an back to int. like:
HashSet<Integer> set = new HashSet<Integer>();
for( int i : x ) {
set.add( Integer.valueOf( i ) );
}
for( int i : y ) {
set.add( Integer.valueOf( i ) );
}
int[] merged = new int[set.size()];
int i = 0;
for( Integer value : set ) {
merged[i++] = value.intValue();
}
That syntax is called varargs - it means it will accept any number of parameters of that type. Removing the generics to simply the explanation, a method defined as this:
public static void someMethod(int... numbers) {
// some code
}
can be called like this:
someMethod(5); // The "numbers" parameter will be an int array size 1: [5]
someMethod(1,2,3); // The "numbers" parameter will be an int array size 3: [1, 2, 3]
someMethod(); // The "numbers" parameter will be an int array size 0: []
It's like a shorthand for this:
someMethod(new int[] {1, 2, 3});
but less ugly.
In your example, the array is a typed generic array - you don't know what the element type is until it's called.
Note:
Following is my homework/assignment, feel free not to answer if you will.
I want to delete/remove an element from an String array(Set) basic, I'm not allowed to use Collections..etc.
Now I have this:
void remove(String newValue) {
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i] == newValue ) {
setElements[i] = "";
}
}
}
I does what I want as it remove the element from an array but it doesn't shorten the length. The following is the output, basically it remove the element indexed #1.
D:\javaprojects>java SetsDemo
Enter string element to be added
A
You entered A
Set size is: 5
Member elements on index: 0 A
Member elements on index: 1 b
Member elements on index: 2 hello
Member elements on index: 3 world
Member elements on index: 4 six
Set size is: 5
Member elements on index: 0 A
Member elements on index: 1
Member elements on index: 2 hello
Member elements on index: 3 world
Member elements on index: 4 six
You can't change the length of an array object once it's created. Here's an excerpt from JLS 10.2. Array Variables:
Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.
This means that for this problem, you'd have to allocate a new array that's one-element shorter than the original array, and copy over the remaining elements.
If you need to remove element at index k, and the original array has L elements, then you need to copy over elements (upper bounds are exclusive):
From [0,k) to [0,k) (k elements)
From [k+1,L) to [k,L-1) (L-k-1 elements).
For a total of L-1 elements copied
static String[] removeAt(int k, String[] arr) {
final int L = arr.length;
String[] ret = new String[L - 1];
System.arraycopy(arr, 0, ret, 0, k);
System.arraycopy(arr, k + 1, ret, k, L - k - 1);
return ret;
}
static void print(String[] arr) {
System.out.println(Arrays.toString(arr));
}
public static void main(String[] args) {
String[] arr = { "a", "b", "c", "d", "e" };
print(arr); // prints "[a, b, c, d, e]"
arr = removeAt(0, arr);
print(arr); // prints "[b, c, d, e]"
arr = removeAt(3, arr);
print(arr); // prints "[b, c, d]"
arr = removeAt(1, arr);
print(arr); // prints "[b, d]"
arr = removeAt(0, arr);
arr = removeAt(0, arr);
print(arr); // prints "[]"
}
This uses System.arraycopy; you can always write your own if this isn't allowed.
static void arraycopy(String[] src, int from, String[] dst, int to, int L) {
for (int i = 0; i < L; i++) {
dst[to + i] = src[from + i];
}
}
This is a simplistic implementation that doesn't handle src == dst, but it's sufficient in this case.
See also
In java to remove an element in an array can you set it to null?
Answer: NO!
Note on == for String comparison
Most of the time, using == to compare String objects is a mistake. You should use equals instead.
String ha1 = new String("ha");
String ha2 = new String("ha");
System.out.println(ha1 == ha2); // prints "false"
System.out.println(ha1.equals(ha2)); // prints "true"
See also
Java String.equals versus ==
Difference Between Equals and ==
why equals() method when we have == operator?
The size of an array in Java can't be changed once the array is created. The following links should help you with transferring the existing items to a new array :-)
See: System.arraycopy and Array.copyOf(*).
Basically you need to create a new array which is as long as the old array's length minus 1 and then you need to copy the valid elements from the old to the new array in a loop and then replace the old array with the new array.
Since this is homework, details are left away. Feel free to post a comment for a bit more clarification.
All that setElements[i] = ""; does is change the value of an element in the array. It does not actually remove anything from the array. If you were using a collection class and called remove(i) on it, then you would actually be removing that element from the collection. But here, you're just changing its value. However, arrays in Java have a fixed size and cannot be resized, so there is no way to remove elements from them. The solution, therefore, is to create a new array with a length one shorter than the old one, and then copy all of the values that you want to keep into the new one. So,
Create new array with a length of setElements.length - 1.
Copy all of the elements in setElements into the new array, except for the one which you're looking to remove. Be careful of the fact that the indices into the two arrays will be off by one rather than equal once you've reached the index for the element that you wish to remove.
Set setElements to the new array if you want to keep using the same variable for your array.
void remove(String newValue) {
if(setElements.length == 0) return;
String [] array = new String[setElements.length-1];
int j = 0;
for ( int i = 0; i < setElements.length; i++) {
if ( setElements[i] != newValue ) {
array[j++] = setElements[i];
}
}
setElements = array;
}
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I thought almost all languages, including java, pass array into function as reference (modifiable).
But somehow it does not work here, and the testArray is still 1,2,3 with size of 3.
Strange enough, when if I change result[i] = 2 to a[1] =2 it works. It did pass by reference.
What is wrong with this code?
At the end, I had a = result; (which update the a). Did result get removed from stack. Is that why I still get to the original a?
I am confused.
Thanks!
class Test
{
public static void main(String[] args)
{
int[] testArray = {1,2,3};
equalize(testArray, 6);
System.out.println("test Array size :" + testArray.length);
for(int i = 0; i < testArray.length; i++)
System.out.println(testArray[i]);
}
public static void equalize(int[] a, int biggerSize)
{
if(a.length > biggerSize)
throw new Error("Array size bigger than biggerSize");
int[] result = new int[biggerSize];
// System.arraycopy(a, 0, result, 0, a.length);
// int array default value should be 0
for(int i = 0; i < biggerSize; i++)
result[i] = 2;
a = result;
}
}
The array is passed by reference, but the reference is passed by value. That is, you can change the array that a refers to, but you cannot change which array a refers to.
Java is pass by value. This is why your code does not work. A good practice would be to mark int[] a as final so this would result in a compilation error (see the corresponding Checkstyle rule).
return parameter "a" from the function and assign to testArray in the main function. When you pass an object by reference, the reference is copied and given to the function. So the object is now referenced by 2 references. Any changes in the object through the 2nd reference will reflect in the first reference, because it is the same object referenced by both of them. But when you change the reference (not the object through reference), it is a different case. you have changed the 2nd reference to point to another object(int[] result). So any changes through the 2nd reference will change only the "result" object.
class Test
{
public static void main(String[] args)
{
int[] testArray = {1,2,3};
testArray = equalize(testArray, 6);
System.out.println("test Array size :" + testArray.length);
for(int i = 0; i < testArray.length; i++)
System.out.println(testArray[i]);
}
public static int[] equalize(int[] a, int biggerSize)
{
if(a.length > biggerSize)
throw new Error("Array size bigger than biggerSize");
int[] result = new int[biggerSize];
// System.arraycopy(a, 0, result, 0, a.length);
// int array default value should be 0
for(int i = 0; i < biggerSize; i++)
result[i] = 2;
a = result;
return a;
}
}
When you do a = result; object a dosnt anymore point to the testArray, bc you are changing its reference to result's address. That's why it dosnt effect anymore to the testArray.
What you are doing actually is you are making a the same adress as result has, so whatever you change in a it will change in result too.
Hope this helped...
The array referenced by a can be modified, but the reference itself is passed by value. So if you did a[0] = 1, then you would be changing the original array. However, a = result changes the reference, and so the original reference is unchanged.
Java is pass by value, always.
Arrays are Objects in java. If you have initialized your array with a size(actually length), you cannot modify it. You can create a new Array with a varying size (as you are currently doing in the function ) and copy all the values from the Old Array to the new Array. In your case, you have 2 objects and 3 references. If you want to access the Array of greater size in the calling function , make the function return the reference of the Array of greater size.
public class test
{
public static void main(String[] args){
int[] a = {15, 2, -3};
printArray(a);
changeArray(a);
printArray(a);
}
private static void changeArray(int[] a){
for(int i = 0; i < a.length; i++){
a[i]++;
}
}
private static void printArray(int[] a){
for(int i = 0; i < a.length; i++){
System.out.print(a[i] + " ");
}
System.out.println();
}
}
-----OUTPUT-----
15 2 -3
16 3 -2