java 创建一个仅包含字符串的 ArrayList。使用增强的 for 循环打印

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13188802/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:49:21  来源:igfitidea点击:

Create an ArrayList only containing Strings. Print using enhanced for loop

javastringfor-looparraylist

提问by RazaHuss

So here is my program:

所以这是我的程序:

Create an ArrayList that will only contain strings Add the following to the list in order

创建一个仅包含字符串的 ArrayList 按顺序将以下内容添加到列表中

  • Mary
  • John
  • Mahendra
  • Sara
  • Jose
  • Judy
  • 玛丽
  • 约翰
  • 马亨德拉
  • 萨拉
  • 何塞
  • 朱迪

Print the list using the enhanced for loop Insert Harry in front of Mahendra and after John Then Remove position 4 from the list

使用增强的 for 循环打印列表 在 Mahendra 前面和 John 后面插入 Harry Then 从列表中删除位置 4

Here's what I've written:

这是我写的:

import java.util.ArrayList;
import java.util.Scanner;

public class Name {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<String>();
        Scanner input = new Scanner(System.in);
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());
        names.add(input.nextLine());

        for (String n : names) {
        System.out.println(n);
        }
    }
}

I guess I'm having problems with adding and removing. I believe everything else should be fine though.

我想我在添加和删除时遇到了问题。我相信其他一切都应该没问题。

采纳答案by Yogendra Singh

You may want to use below methods to insert and remove:

您可能需要使用以下方法来插入和删除:

void    add(int index, E element)
 E      remove(int index)

e.g. Mahendrais at index 2(index starts from 0), then to add Harryin front of Mahendra, just do as below:

例如Mahendra在索引2(索引从0开始),然后Harry在前面添加Mahendra,只需执行以下操作:

  names.add(2, "Harry"); //This will push Mahendra at index 3

To remove crrent index 4,

要删除 crrent 索引 4,

  names.remove(4);

To remove previous index 4, which has become index 5 now,

要删除以前的索引 4,现在已成为索引 5,

  names.remove(5);

回答by Adam

indexOf() will let you find position of a given entry, add(index, object) will let you insert at an index.

indexOf() 会让你找到给定条目的位置, add(index, object) 会让你在索引处插入。

public static void main(String[] args) {
    List<String> names = new ArrayList<String>();

    names.add("Mary");
    names.add("John");
    names.add("Mahendra");
    names.add("Sara");
    names.add("Jose");
    names.add("Judy");

    names.add(names.indexOf("Mahendra"), "Harry");

    for (String name : names) {
        System.out.println(name);
    }
}