java ArrayList replaceAll() 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13256705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ArrayList replaceAll() not working
提问by AllainLG
I don't know what's the problem in my code.Whatever I try to replace, not wroking.
I have a private static ArrayList<String> lista
.
我不知道我的代码有什么问题。无论我尝试替换什么,都不行。我有一个private static ArrayList<String> lista
.
I fill this. Then later in another method, whatever I try, I can't replace anything, like this:
我填这个。然后在另一种方法中,无论我尝试什么,我都无法替换任何东西,如下所示:
public static void replacing() {
Collections.replaceAll(lista, "a", "!!!!!!!!!!!!!!!!!!!!!");
}
Then I print this in the method and lista is the same, nothing changed. What should I check after?
然后我在方法中打印这个,lista 是一样的,没有任何改变。我应该检查什么?
public class MyProgram {
private static ArrayList < String > lista;
public static void fileReading() {
lista = new ArrayList < String > ();
try {
inp = new LineNumberReader(new BufferedReader(new InputStreamReader(new FileInputStream(inFileNev), "ISO8859-1")));
String sor;
while ((sor = inp.readLine()) != null) {
lista.add(sor);
lista.add(System.getProperty("line.separator"));
}
inp.close();
} catch...
}
public static void searching() {
Collections.replaceAll(lista, "a", "b");
System.out.println(lista.toString());
}
}
回答by Ajay George
List<String> list = Arrays.asList(new String[] {"a","b"});
System.out.println(list);
Collections.replaceAll(list, "a", "!!!!!");
System.out.println(list);
gives
给
[a, b]
[!!!!!, b]
The above code sample shows that Collections.replaceAll
indeed works.
上面的代码示例表明Collections.replaceAll
确实有效。
回答by Santosh Gokak
This is an example explaining Collections.replaceAll
这是一个解释 Collections.replaceAll 的例子
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> sLst = new ArrayList<String>();
sLst.add("A");
sLst.add("B");
sLst.add("C");
sLst.add("A");
// This will replace all "A" with "Z"
Collections.replaceAll(sLst, "A", "Z");
System.out.println(sLst);// [Z, B, C, Z]
}
}
回答by Ankur
List<String> list = Arrays.asList(new String[] {"a","ba",new String("a")});
Collections.replaceAll(list, "a", "!!!!!");
System.out.println(list);
output would be
输出将是
!!!!! ba !!!!!
!!!!! ba !!!!!
it would not replace 'a' in "ba"
它不会替换“ba”中的“a”