Varargs method modifies caller's array instead of its own copy? - java

I have this simple varargs method which divides each item in the list:
import java.util.*;
class A {
static long f(long... xs) {
Arrays.sort(xs);
long y = 100000000;
for (int i = xs.length - 1; i >= 0; i--)
y /= xs[i];
return y;
}
static {
System.out.println(f(5,2,6,3,9,3,13,4,5));
long[] xs = new long[]{5,2,6,3,9,3,13,4,5};
System.out.println(Arrays.toString(xs));
System.out.println(f(xs));
System.out.println(Arrays.toString(xs));
}
}
I'd expect it to pass a copy of the array, but apparently it's somehow modifying the array I pass in, instead of its own local copy:
$ javac A.java && java A
79
[5, 2, 6, 3, 9, 3, 13, 4, 5]
79
[2, 3, 3, 4, 5, 5, 6, 9, 13]
So I wrote this simple test program:
class B {
static void f(Object... os) {
System.out.println(os);
}
static {
Object os = new Object[]{1,2,3};
System.out.println(os);
f(os);
}
}
And it does what I expect, it clones the object array before passing it into f (hence different object identifiers):
$ javac B.java && java B
[Ljava.lang.Object;#1242719c
[Ljava.lang.Object;#4830c221
So how then is f in A modifying the caller's array instead of its own copy?

It looks like you've tricked yourself here:
Object os = new Object[]{1,2,3};
System.out.println(os);
f(os);
Since os is typed as Object, it gets interpreted as the first element of the varargs array. What gets passed into the method is actually a new Object[] whose single element is your Object[].
If you do the following, it will print the same instance:
Object[] os = new Object[]{1,2,3};
System.out.println(os);
f(os);
The f method will need make a defensive copy of the array itself in order to guarantee that an array passed in by the caller isn't modified. As arshajii points out, varargs are foremost array parameters, with the "bonus" behavior of creating a new array when given an argument list.
Anyway you can use Arrays.copyOf to make the copy, which delegates to (the less type-safe) System.arraycopy.

varargs is an array type, but with syntactic sugar to allow an on-the-fly array creation if elements are passed separately as parameters.
That is, these two signatures are identical:
static long f(long... xs) {
static long f(long[] xs) {
Except that the varargs may be called with separate elements instead of an array
Of course the array will get modified if you bypass the on-the-fly creation and create an array yourself to pass in.

So how then is f in A modifying the caller's array instead of its own copy?
It doesn't have its own copy. It has a reference to the caller's array.

In the end, an array is an object, so you don't modify the array reference itself instead its contents which is allowed.

Related

One dimensional array in Java

When I run this code on cmd prompt with statement :
java Test A
output is
a
b
c
Wasn't it suppose to result in an error since dimension of args is 1 whereas dimension of x is 3 (args=x).
class Test
{
public static void main(String args[])
{
String[] x={"a","b","c"};
args=x;
for(String i: x)
{
System.out.println(i);
}
}
}
well, the array variable in java is only a reference, so if you give it another reference for a String array it will accept it, so the range of values the array variable(args) accepts is the references to String arrays at memory, it's like changing the value of an integer from 1 to 3, it's ok because they're both valid, and in the range that the integer accepts.
It will not result in an error because your object is not final and you are not changing the array object.
here
double[] data = new double[5]{2, 4, 5, 6, 8} // data can change but the instance of the class cant change
double[] data = new double[7] // here you are changing the data but not the object i.e the created instance of the object does not change but the instance the data(the variable) is holding changes
I hope you got your answer

Why is reading an array within a lamda expression resulting in an error?

In the two examples, the first compiles without error, but the second results in the error "Local variable values defined in an enclosing scope must be final or effectively final" where I attempt to call assertThrows. Why? I am not modifying the array in either case. In fact I copy and pasted the assertThrows line from the first example into the second example and only changed the index used. I'm struggling to understand how to fix the error.
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
class ArrayTests {
#SuppressWarnings("unused")
#Test
void TestArrayException() {
int[] values = new int[5];
assertEquals(0, values[0]);
// here I am reading values within a lamda expression and it works without compiler error.
assertThrows(IndexOutOfBoundsException.class, () -> { int value = values[17]; });
}
/**
* Since arrays can't be resized copyOf can build a new copy with the new length
* truncating or increasing the size of the array with default values.
*/
#SuppressWarnings("unused")
#Test
void TestCopyOf() {
int [] values = {1, 2, 3, 4, 5};
values = Arrays.copyOf(values, 7);
assertEquals(values.length, 7);
assertEquals(values[5], 0);
assertEquals(values[6], 0);
values = Arrays.copyOf(values, 2);
assertEquals(values.length, 2);
assertEquals(values[0], 1);
assertEquals(values[1], 2);
// error occurs in the next line accessing the values array.
assertThrows(IndexOutOfBoundsException.class, () -> { int value = values[3]; });
}
}
The assertThrows is checking that you are using a final or effectively final variable (that cannot be modified).
But in your code, you reassign the variable values.
You should just use an another one:
#Test
void TestCopyOf() {
int [] values = {1, 2, 3, 4, 5};
int [] firstArray = Arrays.copyOf(values, 7);
assertEquals(firstArray.length, 7);
assertEquals(firstArray[5], 0);
assertEquals(firstArray[6], 0);
int [] secondArray = Arrays.copyOf(values, 2);
assertEquals(secondArray.length, 2);
assertEquals(secondArray[0], 1);
assertEquals(secondArray[1], 2);
assertThrows(IndexOutOfBoundsException.class, () -> { int value = secondArray[3]; });
}
Remember that a lambda is just syntactic sugar for creating an anonymous inner class implementing (in your case) IntSupplier (resulting in a class named e.g. ArrayTests$27).
So the rules for inner classes apply. ArrayTest$27 instances can't access the local variables from any currently-executing method of ArrayTest, just like any other class can't do that.
So, when your lambda seems to access the values array (it's just a clever illusion!), in reality the array from values gets passed into the (invisible) constructor of ArrayTests$27, and gets stored as a hidden field of that class, and it's that field that the lambda code really accesses.
Of course, this copy of values doesn't change when you re-assign the values variable itself, so this would break the illusion of accessing the original values variable. To the language designers, keeping up the illusion seemed important, so they allowed "access" only to variables that don't change - originally only those marked final, later also allowing those without any re-assignment, even without the keyword.
Coming back to your code example:
In the first method, you don't re-assign values, so the compiler can keep up the illusion with the copying trick.
In the second method, you do re-assign values, so the compiler refrains from keeping up the illusion. In theory, it would be possible to keep it up, as you don't modify values after the moment you create the lambda. But that's not part of the language specification.

Reading and setting byte[] in function

I need to pass a byte[] in a Java method, and inside the method i need to "change" the byte[], but i don`t want to change the local byte[], i want to change the passed byte[] to the method, like a pointer, for example.
byte[] arr = new byte[10];
doSomethingWithByteArr(arr);
// And now, arr would have changed...
Java is pass-by-reference-value when passing non-primitive arguments to methods, and is pass-by-value when passing primitives, meaning that if you have a byte array and you pass it to a modification method, that object will be modified.
Example:
public static void main(String[] args) {
byte[] arr = new byte[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
// arr now contains { 0, 1, 2, 3, ... 9 }
System.out.println(Arrays.toString(arr));
randomize(arr);
// arr now contains (ex.) { 6, 3, 7, 1, 9, 3, 2, 6, 3, 0 }
System.out.println(Arrays.toString(arr));
}
public void randomize(byte[] arr) {
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(10);
}
}
Not sure if i understand your dilemma.
Java passes its parameters by value every time. This meaning if its a primitive it passes the value of it, and if its an object or array, it passes the value of the object referenced by it.
So if you pass an array you can modify it and since its an alias it will be reflected on the array outside of the method. But you wont be able to point the arr variable to a new reference from within the method code, you could return a new byte[] and assigning to it if you want to change it.
To my knowledge, Java doesn't support passing parameters by reference.
In Java only primitive types are copied when passed to a function. That pseudocode should work as you expect.
Although in Java everything is passed by copy, non primitive types are actually references, that's why your byte[] refers to the same instance inside and outside the function.

Writing `double...` instead of `[] double`

public MonomialPolynomial(double... coeffs){
List<IMonom> monoms = new ArrayList<IMonom>();
for (int i = 0; i < coeffs.length; i++) {
// zero coeffs might yaffect the degree
if(coeffs[i] != 0)
monoms.add(new Monom(coeffs[i], i));
}
super.monoms = monoms;
}
Why do people write double... and not [] double when they mean to array?
Is there a special meaning for this?
double... declares it a "var args" parameter -- inside your method it's identical to double[] but for the caller, it's much easier to call with varying numbers of arguments (hence var args) without the need to explicitly create an array:
Without var args:
MonomialPolynomial(double[] coeffs) { ...}
...
// explicit array creation necessary
new MonomialPolynomial(new double[] {1, 2, 3)};
With var args:
MonomialPolynomial(double... coeffs) { ...}
...
// array gets created implicitly, so less boilerplate code
new MonomialPolynomial(1, 2, 3);
Edit: One thing to watch out for with var args, only the last argument of a method can be a var args argument. This guarantess there's no ambiguity when calling a method, e.g.
foo(int a, int b...) is unambigious, because the first argument will always be assigned to a and anything after that will be go into of b.
foo(int a..., int... b) on the other hand is ambigious, there's no way to tell if foo(1, 2, 3) means a={1} and b={2, 3} or a={1, 2} and b={3}.
double... is a varargs (variable arguments) feature. This means you can provide the constructor with an array of doubles, or you can provide the constructor with any number of doubles, and it is put into an array for you. (Example: MonomialPolynomial(1.0, 5.0, 6.0).)
It is the vararg feature, that is, all the arguments the function gets are collected into an array. In that case, an array of doubles. The feature is for hardcoded arrays and such. If MonomialPolynomial were to accept a double[], you would have to use such oneliners:
MonomialPolynomial(new double[] {1, 2, 3});
But with variable arguments you may write a bit neater code:
MonomialPolynomial(1, 2, 3);

Generic Method is not working

I'm trying to use this method but I get an error in Eclipse saying the type argument is incorrect and it tells me to change the method signature. Any reason why?
/**Creates an independent copy(clone) of the T array.
* #param array The 2D array to be cloned.
* #return An independent 'deep' structure clone of the array.
*/
public static <T> T[][] clone2DArray(T[][] array) {
int rows=array.length ;
//clone the 'shallow' structure of array
T[][] newArray = array.clone();
//clone the 'deep' structure of array
for(int row=0;row<rows;row++){
newArray[row]=array[row].clone();
}
return newArray;
}
The copy2DArray method you posted appears to work as advertised. Perhaps you are calling the method incorrectly? Also make sure you are not using primitive types instead of objects in the array you are copying. In other words, use Integer instead of int.
Here is an example of the working method:
public class Main {
// ...
// Your copy2DArray method goes here
// ...
public static void main(String[] args) {
// The array to copy
Integer array[][] = {
{0, 1, 2},
{3, 4, 5},
{6, 7, 8}
};
// Create a copy of the array
Integer copy[][] = clone2DArray(array);
// Print the copy of the array
for (int i = 0; i < copy.length; i++) {
for (int j = 0; j < copy[i].length; j++) {
System.out.print(copy[i][j] + " ");
}
System.out.println();
}
}
}
This code will print:
0 1 2
3 4 5
6 7 8
It works with all classes. It doesn't work with primitives (int, long, etc.)
So instead of using primitive arrays use the wrapper classes: use Integer[][] instead of int[][].
You can use commons-lang ArrayUtils.toPrimitive(..) and ArrayUtils.toObject(..) to convert arrays between primitives and their wrappers.
You may be using primitive types, when there's no erasure for primitive types. i.e., int.class is completely impossible, but Integer.class works. Wherever generics are involved, primitive types are a no-go.

Categories