Android 开发中实现ArrayList和数组的相互转换
#
1.List转换成为数组。(这里的List是实体是ArrayList)
1.1调用ArrayList的toArray方法。
1.1 toArray
public T[] toArray(T[] a)返回一个按照正确的顺序包含此列表中所有元素的数组;返回数组的运行时类型就是指定数组的运行时类型。如果列表能放入指定的数组,则返回放入此列表元素的数组。否则,将根据指定数组的运行时类型和此列表的大小分配一个新的数组。
如果指定的数组能容纳列表并有剩余空间(即数组的元素比列表的多),那么会将数组中紧跟在集合末尾的元素设置为 null。这对确定列表的长度很有用,但只 在调用方知道列表中不包含任何 null 元素时才有用。
1.2 指定者:
接口 Collection 中的 toArray
指定者:
接口 List 中的 toArray
覆盖:
类 AbstractCollection 中的 toArray参数:
- a - 要存储列表元素的数组,如果它足够大的话;否则,它是一个为存储列表元素而分配的、具有相同运行时类型的新数组。
- 返回:
包含列表元素的数组。- 抛出:
ArrayStoreException - 如果 a 的运行时类型不是此列表中每个元素的运行时类型的超类型。
具体用法:
List list = new ArrayList();
list.add("1");
list.add("2");
final int size = list.size();
String[] arr = (String[])list.toArray(new String[size]);
2. 数组转换成为List。
2.1 调用Arrays的asList方法.
asListpublic static List asList(T… a)返回一个受指定数组支持的固定大小的列表。(对返回列表的更改会“直写”到数组。)此方法同 Collection.toArray 一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。返回的列表是可序列化的,并且实现了 RandomAccess。
此方法还提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素:
List stooges = Arrays.asList(“Larry”, “Moe”, “Curly”);- 参数:
a - 支持列表的数组。
返回:
指定数组的列表视图。
另请参见:
Collection.toArray()
具体用法:
String[] arr = new String[] {“1”, “2”};
List list = Arrays.asList(arr);
数组->List (StringArrayTest.java)
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class StringArrayTest
{
public static void main(String[] args)
{
String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<string> wordList = Arrays.asList(words);
for (String e : wordList)
{
System.out.println(e);
}
}
}
2.2 比较傻的做法
String[] words = { ... }; List<string> list = new ArrayList<string>(words.length); for (String s : words) { list.add(s); }
2.3 另外一种方法:
import java.util.Collections; List myList = new ArrayList(); String[] myStringArray = new String[] {"Java", "is", "Cool"}; Collections.addAll(myList, myStringArray);