Java 中的 For-Each 和指针

问题描述:

好的,所以我很想遍历一个 ArrayList 并删除一个特定的元素.但是,我在使用 For-Each 之类的结构时遇到了一些麻烦.当我运行以下代码时:

Ok, so I'm tyring to iterate through an ArrayList and remove a specefic element. However, I am having some trouble using the For-Each like structure. When I run the following code:

ArrayList<String> arr = new ArrayList<String>();
//... fill with some values (doesn't really matter)

for(String t : arr)
{
  t = " some other value "; //hoping this would change the actual array
}

for(String t : arr)
{
  System.out.println(t); //however, I still get the same array here
}

我的问题是,如何使 't' 成为指向 'arr' 的指针,以便我能够在 for-each 循环中更改值?我知道我可以使用不同的结构遍历 ArrayList,但是这个结构看起来非常干净和可读,如果能够将 't' 设为指针就太好了.

My question in, how can I make 't' a pointer to 'arr' so that I am able to change the values in a for-each loop? I know I could loop through the ArrayList using a different structure, but this one looks so clean and readable, it would just be nice to be able to make 't' a pointer.

感谢所有评论!即使你说我应该接受它并使用不同的结构.

All comments are appreciated! Even if you say I should just suck it up and use a different construct.

我认为最好的方法可能是使用 for 循环.

I think the best approach may be to use a for loop.

    ArrayList<String> arr = new ArrayList<String>();

    for (int i = 0; i < arr.size(); i++) {

        String t = arr.get(i);

        if (// your condition is met) {
            arr.set(i, "your new value");
        }
    }