我想跳过添加存储在数组中的相同值

时间:2013-05-16 12:46:13

标签: java arrays

我在cardlist数组中添加了一些数组索引。我想避免添加那些索引 具有相同的价值。我需要改变什么?

playerHand.player_hand.add(cardList.get(lastCardIndex));
playerHand.player_hand.add(cardList.get(lastCardIndex - 1));
playerHand.player_hand.add(cardList.get(lastCardIndex - 2));
playerHand.player_hand.add(cardList.get(lastCardIndex - 3));
playerHand.player_hand.add(cardList.get(lastCardIndex - 4));

3 个答案:

答案 0 :(得分:1)

您应该使用Set

Set<Integer> cardIndexes = new HashSet<Integer>();

它保证了添加到其中的值的唯一性。

如果最后需要数组,可以使用toArray() Set方法来实现此目的。

Here您可以找到有关Set

的详细信息

答案 1 :(得分:1)

您可以使用Set

  

包含无重复元素的集合。

然后您可以使用Set#toArray()

  

返回一个包含此集合中所有元素的数组。

您还可以从ArrayList

获得Set
List<Integer> list = new ArrayList<Integer>(yourSet);

答案 2 :(得分:1)

你可以像这样使用hashset。

HashSet <Integer> arr1=new HashSet<Integer>();
arr1.add(1);  
arr1.add(2);  
arr1.add(2);  
arr1.add(1);