在java中连接到列表中的最后一个元素
如何连接到列表中的最后一个元素在java中连接到列表中的最后一个元素,java,list,concatenation,Java,List,Concatenation,如何连接到列表中的最后一个元素 List<String> x = {cow, cat, dog}; //explanation purpose List x={cow,cat,dog}//解释目的 如果if语句被触发,我想将“dog”连接为“dogs”。问题是字符串是不可变的,所以当您这样做时 x.get(x.size() - 1).concat("s"); 您只需创建一个附加了“s”的新字符串,但不会更改列表中的字符串。相反,您必须用新字符串替换该位置的元素: Lis
List<String> x = {cow, cat, dog}; //explanation purpose
List x={cow,cat,dog}//解释目的
如果if语句被触发,我想将“dog”连接为“dogs”。问题是字符串是不可变的,所以当您这样做时
x.get(x.size() - 1).concat("s");
您只需创建一个附加了“s”的新字符串,但不会更改列表中的字符串。相反,您必须用新字符串替换该位置的元素:
List<String> x = Arrays.asList("cow", "cat", "dog");
x.set(x.size() - 1, x.get(x.size() - 1) + "s"); // or concat, if you prefer
System.out.println(x);
List x=Arrays.asList(“奶牛”、“猫”、“狗”);
x、 set(x.size()-1,x.get(x.size()-1)+“s”);//如果你愿意的话,也可以吃海螺
系统输出println(x);
下面的例子怎么样:
int index = x.size()-1;
String lastElement = x.remove(index);
x.add(lastElement + "s");
String old = tempSourecode.get(tempSourecode.size()-1)
tempSourecode.set(tempSourecode.size()-1, old + "s");
这显示每个步骤有点冗长,但您可以将其重构为更简单的内容。根据您的评论,您可以尝试以下操作:
int index = x.size()-1;
String lastElement = x.remove(index);
x.add(lastElement + "s");
String old = tempSourecode.get(tempSourecode.size()-1)
tempSourecode.set(tempSourecode.size()-1, old + "s");
你可以这样做
List<String> list = new ArrayList<String>();
list.add("cow");
list.add("cat");
list.add("dog");
list.set((list.size()-1),list.get(list.size()-1).concat("s"));
List List=new ArrayList();
列表。添加(“cow”);
列表。添加(“cat”);
列表。添加(“狗”);
list.set((list.size()-1)、list.get(list.size()-1)、concat(“s”);
获取最后一个元素:x.Get(x.size()-1)代码>,但请注意字符串是不可变的对象,您不能更改它们,但可以用新对象替换它们。tempSourecode.get(tempSourecode.size()-1).concat(“+iterator.next());我已经试过了。事实并非如此working@MarounMaroun谢谢我让它工作了。:)是的,我忘了字符串是不可变的。谢谢,我忘了字符串是不可变的。谢谢,我忘了字符串是不可变的。感谢这不会更改列表中的值@tobias_k-我之前误解了这个问题。修正了我的答案,现在。谢谢你的提醒。干杯