Casting issue with ArrayList toArray() method

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?


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?

Need Your Help

What is the best way to get node value by using XPath API in C#?

c# xml xpath

What is the best way to get node value by using XPath API in C#?

What's the right way to overload the stream operators << >> for my class?

c++ operator-overloading stream-operators

I'm a bit confused about how to overload the stream operators for my class in C++, since it seems they are functions on the stream classes, not on my class. What's the normal way to do this? At the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.