java - 我如何将数组转换为数组列表并对其进行更改以反射(reflect)在数组中?

标签 java arrays arraylist

我想将数组转换为 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&lt;String&gt; 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/

相关文章:

java - 如何获取 Maven 项目的外部依赖项的聚合列表?

Java数组通过类构造函数初始化(性能问题)

java - FixtureList生成器问题java

java - 从另一个ArrayList复制过来的ArrayList<Object>即使有数据也是空的

java - java中ArrayList转Hashset

javascript - 如何在 linux 或 windows 上将 java 导出到 jar

java - 如何将 map api key 存储在 local.properties 中并在 AndroidManifest.xml 中使用

java - Hibernate 保存返回错误的生成 ID

c - 添加数组元素的总和给出了错误的输出?

java - Java中的深拷贝数组