0

I am working on part of a quiz(homework) and one part of my code I need to pass values FROM ArrayList[] locations TO int[] intArray. How is this done?? Thank you.

1. ArrayList locations = new ArrayList();
2. int anArray = locations.size();
3. int[] intArray = new int[anArray];

Thank you

GenericJon
  • 8,746
  • 4
  • 39
  • 50
Bart g
  • 587
  • 2
  • 13
  • 28

3 Answers3

0

Does he mean this?

ArrayList<Integer> locations = new ArrayList<Integer>();
int anArray = locations.size();
int[] intArray = new int[anArray];
int i = 0;
for(int location : locations){
   intArray[i++] = location;
}
AlanFoster
  • 8,156
  • 5
  • 35
  • 52
0

Assuming you have an ArrayList of Integer objects, you can simply loop through the ArrayList and put the elements in intArray like so:

for (int index = 0; index < locations.size(); index++) {
    intArray[index] = (Integer) locations.get(index);
}

Hope that helps.

Andy Zhang
  • 8,285
  • 1
  • 37
  • 24
0

How about using toArray():

ArrayList locations = new ArrayList();
int anArray = locations.size();
int[] intArray = new int[anArray];
intArray = locations.toArray();