2016-11-13 22 views
0

我是標題狀態,我無法爲存儲在linkedlist中的字符串分配隨機數值。這是我linkedlist如何爲存儲在鏈表中的字符串分配隨機數(0-10)

List<String> genres = new LinkedList<>(); 

     attributes.add("Action"); 
     attributes.add("Comedy"); 
     attributes.add("Documentary"); 
     attributes.add("Romance"); 
     attributes.add("Drama"); 

我想出了這樣的事情,但我意識到它是一個數組,而不是linkedlist

Random ran = new Random(); 

String genres_ran = genres[ran.nextInt(genres.length)]; 

我非常感謝任何幫助,非常感謝!

+0

使用genres.get(ran.nextInt(genres.size()))通過索引 –

+0

訪問'LinkedList'其實並不是最大的想法,因爲運行時是'爲O(n )'。根據你的用例,你可能會更好地使用'ArrayList'。 – hendrik

+0

請閱讀[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve) –

回答

1

如果你想分配隨機數字符串,使用地圖數據結構。

然而,看着你的嘗試,似乎你想要從列表中的隨機成員。這樣做:

String randomGenre = genres.get(new Random().nextInt(genres.size())); 
+0

謝謝Bijay,我會試試看。 – TheNoviceProgrammer

相關問題