0 votes
1 view
in Java by (3.6k points)

Basically I have an ArrayList of locations:

ArrayList<WorldLocation> locations = new ArrayList<WorldLocation>();

below this I call the following method:

.getMap();

the parameters in the getMap() method are:

getMap(WorldLocation... locations)

The problem I'm having is I'm not sure how to pass in the WHOLE list of locations into that method.

I've tried

.getMap(locations.toArray())

but getMap doesn't accept that because it doesn't accept Objects[].

Now if I use

.getMap(locations.get(0));

it will work perfectly... but I need to somehow pass in ALL of the locations... I could of course make keep adding locations.get(1), locations.get(2) etc. but the size of the array varies. I'm just not use to the whole concept of an ArrayList

What would be the easiest way to go about this? I feel like I'm just not thinking straight right now.

1 Answer

0 votes
by (34.9k points)

Try the toArray(T[] arr) method.

.getMap(locations.toArray(new WorldLocation[locations.size()]))

(toArray(new WorldLocation[0]) also works, but you would allocate a zero length array for no reason.)

Here's a whole example:

public static void method(String... strs) {

    for (String s : strs)

        System.out.println(s);

}

...

    List<String> strs = new ArrayList<String>();

    strs.add("hello");

    strs.add("wordld");

    method(strs.toArray(new String[strs.size()]));

    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

...

This post has been edited as an article here.

...