我想将数组转换为 Arraylist。但我不想制作该数组的新副本。我希望 Arraylist 成为该数组的引用。
例如
var arr[] = {"abc","def","ghi"}
List tempList = new ArrayList();
for(String val:arr){
tempList.add(val)
}
for(Iterator iterator= tempList.listIterator();tempList.hasNext()){
String temp = iterator.next();
if(temp == "def"){
tempList.remove(temp);
}
}
arr = tempList.toArray(tempList.size());
现在这是我实际想要做的测试示例。我在这里首先操作列表,然后将其转换为数组,然后用列表中的新数组替换“arr”。 但是,如果我从模板列表中删除一个值,那么它是否会像引用值一样从 arr 中删除?
最佳答案
如果您不在列表中添加或删除元素,则可以使用 Arrays.asList
实现。
使用 Arrays.asList(arr)
将为您提供一个由该数组支持的列表。您将能够更改存储在列表中的元素(通过调用 set(int index, E element)
),并将更改反射(reflect)在数组中。但是您不能添加或删除元素,因为数组的长度是固定的。
/**
* Returns a fixed-size list backed by the specified array. (Changes to
* the returned list "write through" to the array.) This method acts
* as bridge between array-based and collection-based APIs, in
* combination with {@link Collection#toArray}. The returned list is
* serializable and implements {@link RandomAccess}.
*
* <p>This method also provides a convenient way to create a fixed-size
* list initialized to contain several elements:
* <pre>
* List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
* </pre>
*
* @param a the array by which the list will be backed
* @return a list view of the specified array
*/
public static <T> List<T> asList(T... a)
关于java - 我如何将数组转换为数组列表并对其进行更改以反射(reflect)在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30231911/