2017-05-04 69 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。

相關問題