我有一个Vector中的对象集,我想从中选择一个随机子集(例如,返回100个项目;随机选择5个)。在我的第一次(非常匆忙)尝试中,我采取了一种极其简单、可能过于聪明的方法:
Vector itemsVector = getItems();
Collections.shuffle(itemsVector);
itemsVector.setSize(5);
虽然这种方法简单方便,但我怀疑它无法很好地扩展,即Collections.shuffle()至少需要O(n)的时间复杂度。我不太聪明的替代方法是
Vector itemsVector = getItems();
Random rand = new Random(System.currentTimeMillis()); // would make this static to the class
List subsetList = new ArrayList(5);
for (int i = 0; i < 5; i++) {
// be sure to use Vector.remove() or you may get the same item twice
subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size())));
}
有没有更好的方法从一个集合中随机选择一个子集?