2015-11-03 70 views
0
private String[] names = { "bobby", "jones", "james", "george", "cletus", "don", "joey" }; 

public String getName() { 
    Random random = new Random(); 
    String name = ""; 
    int num = random.nextInt(names.length-1); 
    name = names[num]; 
    names[num] = null; //HOW TO REMOVE FROM THE LIST??? 
    return name; 
} 

我不記得如何從列表中刪除項目,請幫助。Java - 不記得如何從列表中刪除項目

這是我的解決方案,非常感謝大家!

private String[] names = { "bobby", "jones", "james", "george", "cletus", "don", "joey" }; 
ArrayList<String> list = new ArrayList<String>(Arrays.asList(names)); 

public String getName() { 
    Random random = new Random(); 
    String name = ""; 
    int num = random.nextInt(names.length - 1); 
    name = list.get(num); 
    list.remove(num); 
    return name; 
} 
+3

你不記得,因爲你不能從數組中刪除元素;但你可以創建一個新的數組,並只複製你想要的元素(提示:使用'System.arrayCopy()') – morgano

+0

檢查了這一點http://stackoverflow.com/questions/112503/how-do-i-remove-對象在java中的陣列 – Rockstar

回答

0

在程序中你正在使用字符串數組。如果你想刪除列表元素,那麼你可以用這種方式刪除元素:

for (Iterator<String> iter = list.listIterator(); iter.hasNext();) { 
    String a = iter.next(); 
    if (//remove condition) { 
    iter.remove(); 
    } 
} 

如果你想刪除列表中的所有elemnt那麼你可以使用這條線:

list.removeAll(//Your list); 

你可以做這樣:

String[] names = { "bobby", "jones", "james", "george", "cletus", "don", "joey" }; 
List<String> list = new ArrayList<String>(Arrays.asList(names)); 
Random random = new Random(); 
int num = random.nextInt(names.length-1);  
list.remove(num);  
System.out.println(Arrays.asList(list.toArray(new String[list.size()]))); //Print the value of updated list 
+0

我得到了這個錯誤的for語句,爲「list.listIterator()」:不能調用listIterator()在數組類型字符串[] 順便說一句請記住我有從未使用迭代器的 – IshThaFish

+0

檢查我的更新答案。 –

+0

看看我更新的帖子,這是我用過的,它完美的作品。非常感謝喲,我會+代表你的帖子,但我太低級了。 – IshThaFish

1

數組是固定大小的數據結構。你不能減小它的大小。但是,您可以覆蓋內容並維護一個可以告訴您有效大小的計數器。基本上,你將條目左移一個插槽。

在你的榜樣,你可以做這樣的事情:

讓我們假設你想刪除[5]和有數組中的10個元素。

for(int inx = 5; inx < 9; inx++) 
{ 
    array[inx] = array[inx+1] 
} 
int arrayLength = array.length; // Because you are overwriting one entry. 

有了這個,你的數組現在看起來像

此代碼之前:

"bobby", "jones", "james", "george", "cletus", "don", "joey", "pavan", "kumar", "luke" 

此代碼後:

"bobby", "jones", "james", "george", "cletus", "joey", "pavan", "kumar", "luke", "luke" 

我們已覆蓋 「唐」 項這裏。現在我們必須維護一個新的計數器,它現在將成爲數組的長度,這將比array.length小1。你將使用這個新變量來處理數組。

+0

謝謝我會試試看看它是否有效,如果有的話,我會盡快回復您! – IshThaFish