UDE_Student
UDE_Student

Reputation: 349

Array Clone doesn't work

what is wrong with my code?

in the main method i am doing this:

int [] test=new int[48];

test=etable(Right[]).clone();

What i want is, that the 'test' array is exactly the same like the output of the 'etable' method.

my method called 'etable':

public static int [] etable(int [] right){
int [] blabla=new int[48];
...
return blabla[]
}

Thanks for your advise

Upvotes: 0

Views: 774

Answers (2)

Stephen C
Stephen C

Reputation: 718758

what is wrong with my code?

This line is a compilation error:

    test = etable(Right[]).clone();

If right (or Right) is a variable (declared with type int[]), then you should write the method call like this:

    test = etable(right).clone();

If Right is a type, then that is not the correct syntax for creating an array. (And judging from how you have written the etable method, you should not be passing it a new array.)

The second problem is that this sequence doesn't make sense:

    int test[] = new int[48];
    test = etable(...).clone();

You are allocating an array of 48 elements ... and then throwing it away by assigning a different array reference to the test variable.

The third problem is that the clone() is most likely redundant anyway. Your etable method is allocating a new array (in blabla) and returning it. The calling code is then copying the new array. Unless the etable saves the reference to the blabla array somewhere, the copying step doesn't achieve anything.

The final problem is that if Right really is a variable name, then that is a serious Java style violation. In Java a variable name should NOT start with an upper-case letter.

Upvotes: 5

fge
fge

Reputation: 121712

Use for instance Arrays.copy():

int[] tmp = etable(whatever);
int[] test = Arrays.copy(tmp, 0, tmp.length);

As to your original code, this, for instance:

test = ebtable(Right[]).clone();

is not legal Java (what is Right anyway?).

Upvotes: 1

Related Questions