繁体   English   中英

如何将数组转换为arraylist并对其进行更改以反映在数组中?

[英]How do i convert array into arraylist and make changes to it that will be reflect in the array?

我想将一个数组转换为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)将给您一个由该数组支持的列表。 您将能够更改存储在List中的元素(通过调用set(int index, E element) ),并使更改反映在数组中。 但是您不能添加或删除元素,因为数组的长度是固定的。

/**
 * 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)

您可以做的是编写一个从数组更新ArrayList的方法(这将是参数)。 该方法将更新ArrayList,以使其保留传入的数组的值。给人一种错觉,即数组和ArrayList都是“同步的”,每次更改原始数组时,都必须调用此方法数组。 为了优化该方法,我将为它提供两个参数:数组和ArrayList。 因为ArrayList是对象,所以不需要从方法中返回它,因为实际上您将在方法中更改对象本身。 只需确保将ArrayList传递给方法之前初始化它即可(虽然仅是第一次)。 这是此想法的快速实现:

private void updateArrayList(String[] arr, ArrayList<String> alist) {
    for(int i = 0, n < arr.length; i < n; i++) {
        alist.set(i, arr[i]);
    }
}

如果我输入有误,请发表评论,并请我澄清答案的某些部分是否不清楚。 另外,请告诉我此答案是否有帮助,或者即使我正确解释了问题,也请告诉我。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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