如何从阵列列表中删除元素?

时间:2017-05-04 05:03:51

标签: java arrays arraylist java.util.scanner

所以我想询问用户是否要从数组列表中删除元素。数组列表是从文件中读取的最喜欢颜色的列表。所以我们可以说数组列表的内容是红色,橙色,绿色,蓝色。我想知道如何根据用户输入删除元素。会不会像 -

System.in.println("Which color would you like to remove")
removeColor = reader.nextString
if removeColor (//using pseudo code here) contains removeColor, remove from ArrayList

我是否在正确的轨道上?到目前为止,我的代码。谢谢!

Scanner input = new Scanner(System.in);
        ArrayList <String> favoriteColors = new ArrayList <String>();
        boolean repeat = true;
        while (repeat) {

            System.out.println("Enter the name of the file which contains your favorite colors ");
            String fileName = input.nextLine().trim();

            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

                String line;
                System.out.println("Here are your favorite colors according to the file:");  
                 while ((line = reader.readLine()) != null) {    
                   System.out.println(line);   
                   favoriteColors.add((line));
                 }                                                

                 System.out.println("Add more? (y/n)");
                 if (input.next().startsWith("y")) {
                     System.out.println("Enter : ");
                     favoriteColors.add(input.next());
                 } else {
                     System.out.println("have a nice day");
                 }
                 for (int i = 0; i < favoriteColors.size(); i++) {
                     System.out.println(favoriteColors
                 if (input.next().startsWith("y")) {
                 System.out.println("Remove a color?")
                 if (input.next().startsWith("y")) {
                 /something along the lines of the pseudo code I wrote above

3 个答案:

答案 0 :(得分:2)

您需要了解ArrayList中的remove方法是如何工作的:

方法remove实现如下:

public boolean remove(Object o) {
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
}

表示列表所持有的对象必须能够实现此条件:

if (o.equals(elementData[index])) {

埃尔戈:

如果您的 favoriteColors 类只是字符串,那么它就能正常工作

但如果它们是您自定义的,那么您需要在该类中实现equals。

答案 1 :(得分:0)

您必须循环favoriteColors列表以检查匹配的字符串颜色,如果找到,则使用该索引使用favoriteColors.remove(index)

删除元素

但是我建议使用Set集合而不是List,比如HashSet,所有键都是唯一的,并且在你的情况下包含许多有用的方法,如add(colorString),remove(colorString)和contains(colorString)来检查现有的颜色。 / p>

答案 2 :(得分:0)

您可以遍历arraylist并获取所需元素的索引,

int index = favoriteColors.indexOf("<the color you want to remove>")

然后从arraylist中删除该元素,

    favoriteColors.remove(index);