Array和List相互转化

在做ListView的时候,需要不断的和Adapter打交道,那在这个过程中不免总是会涉及到以下的基本操作:

在代码中获取资源文件中定义的Array数组:

String[] array = getResources().getStringArray(R.array.XXX);

如何把获取到的Array类型转化成代码中需要的List类型:

List<String> list = Arrays.asList(array);

public static List<T> asList (T... array)

Added in API level 1

Returns a List of the objects in the specified array. The size of the List cannot be modified, i.e. adding and removing are unsupported, but the elements can be set. Setting an element modifies the underlying array.

Parameters
array the array.
Returns
  • a List of the elements of the specified array.  

如何把List类型转化成代码中需要的Array类型:

array = list.toArray();

array = list.toArray(new String[list.size()]);

方法原型:

public static List<T> asList (T... array)

Added in API level 1

Returns a List of the objects in the specified array. The size of the List cannot be modified, i.e. adding and removing are unsupported, but the elements can be set. Setting an element modifies the underlying array.

Parameters
array the array.
Returns
  • a List of the elements of the specified array. 

public abstract T[] toArray (T[] array)

Added in API level 1

Returns an array containing all elements contained in this List. If the specified array is large enough to hold the elements, the specified array is used, otherwise an array of the same type is created. If the specified array is used and is larger than this List, the array element following the collection elements is set to null.

Parameters
array the array.
Returns
  • an array of the elements from this List.
Throws
ArrayStoreException if the type of an element in this List cannot be stored in the type of the specified array. 

你可能感兴趣的:(Array和List相互转化)