2013-05-16 36 views
-1

我已经在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)); 

回答

1

您可以使用Set

包含没有重复元素的集合。

然后可以使用Set#toArray()

返回包含所有在该组中的元素的数组。

您也可以从SetArrayList

List<Integer> list = new ArrayList<Integer>(yourSet); 
1

您应该为此使用Set

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

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

如果你最后需要一个数组,你可以使用SettoArray()方法来达到这个目的。

Here你可以找到有关Set的详细信息。

1

您可以使用HashSet的这个样子。

HashSet <Integer> arr1=new HashSet<Integer>(); 
arr1.add(1); 
arr1.add(2); 
arr1.add(2); 
arr1.add(1); 
相关问题