我在 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())));
}
有关从集合中提取随机子集的更好方法的任何建议?