1

我正在尝试从我拥有的给定集合中创建一个由独特成员组成的团队。这就是我到目前为止所拥有的。

import java.util.*;
import java.lang.*;

class Main
{
   public static void main (String[] args) throws java.lang.Exception
   {
        /* Putting all team-mates in HashMap */

        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("a", 1);
        map.put("b", 2);
        map.put("c", 3);
        map.put("d", 4);

        /* Printing out the random name and the Unique number with it*/

        List<Integer> valuesList = new ArrayList<Integer>(map.values());
        List<String> keyList = new ArrayList<String>(map.keySet());
        System.out.println("The Team members are :");
        for (int i = 0; i < 3; i++)
        {
            int randomIndex = new Random().nextInt(valuesList.size());
            Integer randomValue = valuesList.get(randomIndex);
            String randomKey = keyList.get(randomIndex);
            System.out.println(randomValue+" "+randomKey);
        }
    }
}

当我运行它时,我的列表中有重复,我是否使用 Collections.shuffle(valuesList)?

谢谢你。

4

2 回答 2

1

您可以两次随机获得相同的数字,Collections.shuffle(...)应该这样做。

于 2012-11-09T18:38:51.020 回答
0

如果 a,b,c,d 是你所追求的,我会这样做:

import java.util.*;
import java.lang.*;

class Main
{
   public static void main (String[] args) throws java.lang.Exception
   {
        /* Putting all team-mates in a List*/

        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");

        /* Printing out the random name */

        System.out.println("The Team members are :");
        for(int i = 0; i < 3; i++)
        {
            int randomIndex = new Random().nextInt(list.size());
            //Integer randomValue = valuesList.get(randomIndex);
            String randomValue = list.remove(randomIndex);
            //String randomKey = keyList.get(randomIndex);
            System.out.println(randomValue);
        }
    }
}

选择后从列表中删除所选元素将确保它们不会再次出现。

也少了几行。

于 2012-11-09T18:45:16.490 回答