Java,替换列表中的值 [英] Java, replace values in a list

查看:37
本文介绍了Java,替换列表中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题.我想用一个方法列出一个列表,在该列表中找到一个值,然后用另一个替换它.

I have following problem. I want to take a list with a method, find a value within that list and replace it with another.

void replaceAll( ArrayList<Integer> arr, Integer toFind, Integer replacement) {
   int indexOfArray = arr.indexOf(toFind);
   if(arr.contains(toFind)) {
      for(int x = 0; x < arr.size(); x++) {
         if (arr.contains(toFind)) {
            arr.remove(toFind);
            arr.add(indexOfArray, replacement);
         }
      }
   }
}

这是我为自己制定的解决方案,并且肯定可以正常工作.但是,我认为无需使用for循环就可以更干净地完成它.有人可以告诉我如何吗?

This is the solution I have worked out for myself and it most certainly works. However, I think it can be done more cleanly without the usage of a for loop. Could someone tell me how?

推荐答案

有一个内置方法可以完全执行此操作:

There is a built in method to do exactly this operation:

Collections.replaceAll(list, foo, bar);

这篇关于Java,替换列表中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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