1

In one class I have constructor which looks like:

Class(int x, int y, int[] moves);

In other class which creates those objects I have moves stored in ArrayList. Moves are numbers. So when this class decides ti create new object it must first convert this ArrayList into array. So I tried something like this:

new Object(0, 0, (int[])moves.toArray(int[moves.size()]);

But it doesn't work. How should it be done properly?

0

1 Answer 1

5

The result of calling toArray() on an ArrayList is never an int[]. You can't have an ArrayList<int> in Java due to the way generics works. At best it would be an Integer[], which you'd then need to convert. Note that even though you can convert from Integer to int, you can't cast an Integer[] to an int[]. Something has to loop over the values.

You could just do it directly:

int[] values = new int[moves.size()];
for (int i = 0; i < values.length; i++) {
    values[i] = moves.get(i);
}

Alternatively could create an Integer[] and then convert from that - but why do the copying twice?

Sign up to request clarification or add additional context in comments.

3 Comments

No i don't want loop version. So you say it should look like: new Object(0, 0, (Integer[])moves.toArray(new Integer[moves.size()]) ?
@MichałTabor guess you wouldn't need the cast , just moves.toArray(new Integer[moves.size()] would suffice .
@MichałTabor: Well that won't work because your constructor doesn't take an Integer[], does it? Something's going to loop... given that you don't have the right types, it might as well be your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.