Ser*_*gej 4 java random arraylist set sublist
简单地说我的问题是:检索具有给定大小的ArrayList的随机不连续子列表的最有效方法是什么.
以下是我自己的设计,虽然有效,但对我来说似乎有点笨拙.这是我的第一个JAVA程序,所以请原谅我的代码或问题是否符合最佳实践;)
备注:
- 我的列表不包含重复项
- 我猜想如果AimSize超过原始列表大小的一半,删除项目而不是添加项目可能会更快
public ArrayList<Vokabel> subList(int AimSize) {
ArrayList<Vokabel> tempL = new ArrayList<Vokabel>();
Random r = new Random();
LinkedHashSet<Vokabel> tempS = new LinkedHashSet<Vokabel>();
tempL = originalList;
// If the size is to big just leave the list and change size
// (in the real code there is no pass-by-value problem ;)
if (!(tempL.size() > AimSize)) {
AimSize = tempL.size();
// set to avoid duplicates and get a random order
} else if (2* AimSize < tempL.size()) {
while (tempS.size() < AimSize) {
tempS.add(tempL.get(r.nextInt(tempL.size())));
}
tempL = new ArrayList<Vokabel>(tempS);
// little optimization if it involves less loops
// to delete entries to get to the right size, than to add them
// the List->Set->List conversion at the end is there to reorder the items
} else {
while (tempL.size() > AimSize) {
tempL.remove(r.nextInt(tempL.size()));
}
tempL = new ArrayList<Vokabel>(new LinkedHashSet<Vokabel>(tempL));
}
return tempL;
}
Run Code Online (Sandbox Code Playgroud)
警告:这是在我的浏览器中编码的.它甚至可能无法编译!
使用Collections.shuffle和List.subList将完成这项工作.
public static <T> List<T> randomSubList(List<T> list, int newSize) {
list = new ArrayList<>(list);
Collections.shuffle(list);
return list.subList(0, newSize);
}
Run Code Online (Sandbox Code Playgroud)