如何修改String类型LinkedList的内容?附现有代码求指导
嘿,针对你这段代码里的String类型LinkedList,我整理了几种实用的修改方法,帮你快速搞定需求:
首先先贴出你的代码方便参考:
你编写的代码如下:
public static void main(String[] args) { LinkedList<String> list = new LinkedList<>();//declare your list Scanner input = new Scanner(System.in);//create a scanner System.out.println("How many participants? "); int nbr = input.nextInt();//read the number of element input.nextLine(); do { System.out.println("What is the name of the people?"); list.add(input.nextLine());//read and insert into your list in one shot nbr--;//decrement the index } while (nbr > 0);//...
修改String类型LinkedList内容的几种方法
- 按索引直接替换(最直接的方式)
LinkedList自带的set(int index, String newElement)方法就是专门用来替换指定位置元素的。注意索引是从0开始的,使用前要确保索引在0到list.size()-1之间,不然会抛出越界异常。
举个例子,假设你想修改第2个输入的名字(索引1):
// 替换索引1的元素为"新名字" list.set(1, "Emma Updated"); // 打印修改后的列表看看效果 System.out.println("修改后的列表:" + list);
- 按元素内容查找并修改
如果你不知道要改的元素在哪个位置,只知道它的内容,可以先用indexOf()找到对应的索引,再用set()修改。要是元素不存在,indexOf()会返回-1,记得加个判断避免报错。
比如要把名为"Jack"的参与者改成"Jackson":
String oldName = "Jack"; String newName = "Jackson"; int targetIndex = list.indexOf(oldName); if (targetIndex != -1) { list.set(targetIndex, newName); } else { System.out.println("找不到名为" + oldName + "的参与者"); }
- 批量修改符合条件的元素
如果需要批量修改满足特定条件的元素(比如所有带"Li"的名字、所有小写开头的名字),用replaceAll()结合Lambda表达式会非常方便。
比如把所有名字转为大写,或者替换包含"Tom"的名字:
// 把所有名字转为大写 list.replaceAll(String::toUpperCase); // 把所有包含"Tom"的名字改成"Thomas" list.replaceAll(name -> name.contains("Tom") ? "Thomas" : name);
- 遍历过程中修改(用迭代器)
要是你需要一边遍历链表一边修改元素,可以用ListIterator,它支持在迭代时修改当前指向的元素,避免遍历修改时出现并发修改异常。
示例代码:
ListIterator<String> iterator = list.listIterator(); while (iterator.hasNext()) { String currentName = iterator.next(); // 把名为"Charlie"的改成"Charles" if (currentName.equals("Charlie")) { iterator.set("Charles"); } }
小提醒
LinkedList是链表结构,按索引访问元素的效率不如ArrayList(数组结构),如果你的场景需要频繁按索引修改元素,建议考虑换成ArrayList。但如果只是偶尔修改,LinkedList完全够用~
内容的提问来源于stack exchange,提问作者equasezy
相关产品推荐
相关产品推荐

