Java 中的 For-Each 和指针 [英] For-Each and Pointers in Java

查看:29
本文介绍了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");
        }
    }

这篇关于Java 中的 For-Each 和指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆