2017-05-04 146 views
0

所以我想问用户他们是否想从数组列表中删除一个元素。数组列表是从文件读入的喜欢颜色的列表。所以我们可以说数组列表的内容是 - 红色,橙色,绿色,蓝色。我想知道如何删除基于用户输入的元素。它会是这样的 -如何从我的数组列表中删除元素?

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 
+0

只要调用remove,它将删除元素,如果相同的元素在'List'中或者它不是。 – SomeJavaGuy

+0

是的,你在正确的轨道上。看一看Arraylist文档 - https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html,特别是'remove'方法。 – Matt

+0

一个小提示:如果你正在编写一个程序来保存某人喜欢的颜色列表,你可能不需要'favoriteMovies'变量。 – ajb

回答

0

你必须环路favoriteColors列表来检查匹配串色,如果找到,那么使用该索引使用favoriteColors.remove(index)

不过,我建议使用设置集合要删除的元素没有列出,像HashSet的,所有的键都是唯一的,并且包含许多有用的方法,比如add(colorString),remove(colorString)和contains(colorString)来检查现有的颜色。

+0

为什么他需要遍历数组,如果他可以调用'List#remove'?该方法只是删除元素,如果它存在或没有做任何事情 – SomeJavaGuy

+0

List.remove(Object)在内部做同样的循环,然后删除,但如果你知道索引删除索引是更快..我建议在这里如果列表很大,使用Set可以获得更好的性能,因为不会重新编制索引 –

0

你可以通过数组列表遍历,并得到你想要的元素的索引,

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

然后从ArrayList中移除元素,

favoriteColors.remove(index); 
2

你需要了解如何删除方法ArrayList的工作原理:

该方法删除实现如下:

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。