简单地说,我的问题是:如何以最有效的方式检索给定大小的 ArrayList 的随机不连续子列表。
以下是我自己设计的代码,它可以工作,但对我来说似乎有点笨重。顺便说一下,这是我的第一个 JAVA 程序,请原谅如果我的代码或问题不符合最佳实践 ;)
注: - 我的列表不包含重复项 - 如果目标大小大于原始列表的一半,则我“猜测”删除项目可能比添加项目更快
以下是我自己设计的代码,它可以工作,但对我来说似乎有点笨重。顺便说一下,这是我的第一个 JAVA 程序,请原谅如果我的代码或问题不符合最佳实践 ;)
注: - 我的列表不包含重复项 - 如果目标大小大于原始列表的一半,则我“猜测”删除项目可能比添加项目更快
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;
}
List
中有一个subList
方法。 - johnchen902java.util.Collections.shuffle(java.util.List)
。 - johnchen902subList
和一个随机起点... - johnchen902