【问题标题】:How to change content of the String Linked List如何更改字符串链表的内容
【发布时间】:2018-10-07 16:04:11
【问题描述】:

我写了这个:

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);//repeat until the index will be 0

    System.out.println(list);//print your list

输出是:

Jack, Frank

我想做的是改变链表的内容。例如,我写了 2 个名字 Jack 和 Frank。然后我想添加杰克的姓氏,这样链表就会是:

Jack Adam, Frank

我该怎么办?

【问题讨论】:

  • 它只是改变了列表的索引。例如我写了 list.set(0, Adam);它只是用 Adam 创建了一个新节点。不改变内容。
  • 不,它会更改 at 列表中索引的值。 list.set(0, "Jack Adam") 会按照你的要求去做。
  • 我不想再写“杰克”,这就是问题所在。我只想写亚当,它会将“亚当”添加到杰克。
  • 嗯,那你需要获取并设置相同的索引,如Glim的回答所示。

标签: java linked-list


【解决方案1】:

您需要做的是使用set 方法更新您要更新的特定位置。在这种情况下将是这样的:

list.set(0, list.get(0) + " Adam");

请注意,我们正在获取列表位置 0 的内容并与姓氏连接。

【讨论】:

  • 谢谢,这就是我一直在寻找的东西,我将在“您可以在 x 分钟后接受这个”之后将其标记为答案!
猜你喜欢
  • 1970-01-01
  • 2012-10-04
  • 2020-08-12
  • 2022-12-17
  • 2015-08-29
  • 2018-05-17
  • 2011-06-05
  • 2018-11-19
  • 2014-03-08
相关资源
最近更新 更多