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;
}
你不記得,因爲你不能從數組中刪除元素;但你可以創建一個新的數組,並只複製你想要的元素(提示:使用'System.arrayCopy()') – morgano
檢查了這一點http://stackoverflow.com/questions/112503/how-do-i-remove-對象在java中的陣列 – Rockstar