简体   繁体   中英

How to convert ArrayList<Integer> to an int[]?

I have an array that is saved in the strings.xml.
I want to get how many items are there in the list, and then put it in another list.

For example, if the String contains {"One", "Two", "Three"} ,
then I want an int that contains {0,1,2} .

From what I know, the only way to do it is to use the ArrayList , so I could use the add method.

Here is the code I'm using to make this:

String[] names;
ArrayList<Integer> MyList;

for (int i = 0; i < names.length; i++){
  MyList.add(i);
}

But the problem is that I don't know how to change the ArrayList<Integer> into an int[] .
How can this be done?

Check out ArrayList api

Integer[] stockArr = new Integer[yourList.size()];
stockArr = yourList.toArray(stockArr);

Java Supports Auto un-boxing even though.

  int[] finalArr = new int[stockArray.length];
 for(int i=0;i<stackArray.length;i++ )
 {
      int[i] = stocArray[i];
  }

If you want to create an int[] array of numbers from 0 up to names.length , then this is how you do it:

int[] numbers = new int[names.length];
for (int i = 0; i < names.length; i++) {
    numbers[i] = i;
}

For ordinary Object types, you can simply use the ArrayList.toArray() method to convert an ArrayList to an equivalent array of objects. However, in this question, it appears that you are also looking to perform unboxing of the primitive types, as well. To do that, you simply need to directly copy:

 private static int[] convertArrayListToPrimitiveArray(
     ArrayList<Integer> arrayList) {
   int count = arrayList.size();
   int[] result = new int[count];
   for (int i = 0; i < count; i++) {
     result[i] = arrayList.get(i);
   }
   return result;
 }

You can use the function above in your code like this:

ArrayList<Integer> original = ...
int[] equivalentAsArray = convertArrayListToPrimitiveArray(original);

That being said, it is generally preferred/more idiomatic to use the Java collection types over raw arrays in Java code, and doing this conversion is not free (it takes time proportional to the size of the array and it ends up duplicating the amount of memory needed to store the data). So if you can use a Iterable<Integer> , List<Integer> , or ArrayList<Integer> instead of performing this conversion, I'd highly advise that you do so. It may be possible for you to simply use the existing collection rather than performing the conversion (and if you need to pass the raw array to a helper or library method, extending the library to support collection types may be the better approach).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM