2

When declaring and assigning primitives before loop everything works fine and could be different from each other later on

//example
double sum1, sum2, sum3, sum4;
sum1 = sum2 = sum3 = sum4 = 0;
//later each gets own value correctly

Is it possible to make oneliner for an array?

//example
double[][] compare, updated; // works as intended
compare = updated = new double[SIZE][]; // makes compare=updated

Problem with second line is that it ignores all following calculations for updated and takes values from compare.

JayJayAbrams
  • 195
  • 1
  • 16
  • 1
    You can do this with primitives, but not ```Object```. ```Object``` use reference and array in java is ```Object```. – zhh Jul 28 '18 at 05:18

2 Answers2

2

If by "one-liner" you mean a single statement and writing new double[] once, yes you can do this:

    double[] arr1, arr2;
    arr1 = (arr2 = new double[10]).clone(); // this is the line
    arr1[0] = 10;
    System.out.println(arr2[0]); // 0.0

But it's not very readable. It gets even worse when you do this with more arrays:

arr1 = (arr2 = (arr3 = new double[10]).clone()).clone();

I suggest you still use multiple lines to do this.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
2

As an alternative to @Sweeper's answer, consider using the Arrays.copyOf() method, as suggested in this answer. Note that the copyOf() method is type-safe whereas the clone() method isn't.

double[] a, b, c;
c = Arrays.copyOf((b = Arrays.copyOf((a = new double[10]), a.length)), b.length);

But again, I'll reiterate as @Sweeper does, that this code really smells and you should consider doing it in multiple lines. As Steve McConnell says in Code Complete 2nd Ed., the Primary Technical Imperative of software is to manage complexity (i.e. make your code simple). This doesn't necessarily mean reducing the lines of code, but more to do with enabling people who read your code to understand what it does at a glance.

entpnerd
  • 10,049
  • 8
  • 47
  • 68
  • I didn't use `Arrays.copyOf` because I tried to recreate the "feel" of `a = b = c` as much as possible, making the array variables closer. But good answer anyway, +1. – Sweeper Jul 28 '18 at 06:26