Java中有没有复制字符串的好方法?我知道我可以做一些串联黑客,但我想知道是否有更优雅的解决方案。
我想将 ArrayList 中的每个字符串复制一定次数。然而,数组列表似乎不允许同一个对象多次出现。我正在寻找一种复制字符串的方法,以便将其添加到 ArrayList 中。
public class MyClass {
ArrayList<String> myArrayList;
/*more code*/
public ArrayList<String> duplicate(int timesToCopy) {
ArrayList<String> newArrayList = new ArrayList<>();
for(String s: myArrayList) { //cycles through all strings
for(int i = 1; i <= timesToCopy; i++) { //adds them timesToCopy amount of times
newArrayList.add(s); //doesn't work, only adds it once
}
}
return newArrayList;
}
}
如果我在调用重复(3)时输入值为 {"cat", "dog"} 的 ArrayList,我应该得到 {"cat", "cat", "cat", "dog", "dog"、“狗”}
但是,我得到的是 {"cat", "dog"}。
我尝试更换
newArrayList.add(s);
与
newArrayList.add(new String(s));
但是还是不行。
也许我的代码的其他部分有错误?
编辑:
好吧,我不知道发生了什么,但在我什么都没做之后它就以某种方式起作用了。
编辑2:
好吧,问题又出现了。不过,我发现了问题所在!我调用重复(3)就像它是一个void函数一样,认为它会更改实例的ArrayList而不是返回一个新的。我真是太笨了。
最佳答案
我不确定你如何调用你的方法,但我会像这样传入输入List
public static List<String> duplicate(List<String> al, int n) {
List<String> ret = new ArrayList<>();
for (String s : al) {
for (int i = 0; i < n; i++) {
ret.add(s);
}
}
return ret;
}
public static void main(String[] args) {
System.out.println(duplicate(Arrays.asList("dog", "cat"), 3));
}
输出是(根据要求)
[dog, dog, dog, cat, cat, cat]
关于java - 在 Java 中复制字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27118129/