我的代碼中有20個名稱。 我的功能有2個選項的元素添加到列表中我有:列表中的隨機元素添加期間
插入所有20名名單:
public void addNames() {
list.add("name1");
list.add("name2");
...
list.add("name20");
}
2.
僅將5個隨機名稱(來自20個名稱)添加到列表中。爲了做到這一點,我想到了兩種方法。從20中隨機抽取5個名字的最佳方法是什麼?也許你有更好的辦法。
A.
使用一組隨機指標(各值將介於0到19,因爲有20名)和之前的「添加」我會通過一些檢查,如果將它們添加或不計數器:
public void addNames() {
// adding 5 random indices between 0 to 19 to the set
Set<Integer> set = new HashSet<Integer>();
Random r = new Random();
Set<Integer> indices = new HashSet<>(numRandomNames); //==5
for (int i = 0; i < numRandomNames; ++i) {
int index = r.nextInt(numNames - 0); //==19
indices.add(index);
}
int counter = 0;
if (indices.contains(counter)) {
list.add("name1");
}
counter++;
if (indices.contains(counter)) {
list.add("name2");
}
counter++;
if (indices.contains(counter)) {
list.add("name3");
}
...
}
B.擴展列表和覆蓋的 '添加' 功能
RandomList做同樣爲「A.'做,但覆蓋的‘添加’將決定是否加入該函數內的價值,所以我的功能看起來一樣與覆蓋‘添加’功能
你想一個更好的解?如果不是,那哪一個更好? (A或B?)。我剛剛看到人們建議不要擴展java收集,但我認爲這是來自這兩種解決方案的最佳解決方案。
注意
====
我的代碼可以有10000名以上的偶數,所以我不希望所有10000名添加到該\其他列表中,然後隨機其中5個到其他列表。我更喜歡在添加期間這樣做,以避免列表中的許多地方,而我並不真正需要它們。
編輯
回答ProgrammerTrond:
我不知道我會做到這一點,但我要求我展示的是我的2.B的建議:
public class RandomList<Integer> implements List<Integer> {
private int addCallsCounter;
private Set<Integer> setIndices = null;
public RandomList(final int numElements, final int maxVal, final int minVal) {
addCallsCounter = 0;
setIndices = new HashSet<Integer>(numElements);
Random r = new Random();
while (setIndices.size() < numElements) {
int index = r.nextInt(maxVal - minVal + 1) + minVal;
if (setIndices.contains(index) == false) {
setIndices.add(index);
}
}
}
@Override
public boolean add(Integer object) {
if (setIndices.contains(addCallsCounter++)) {
this.add(object);
return true;
}
return false;
}
}
,並從我的代碼,我會這麼做:
RandomList randList = new RandomList(5);
randList.add("name1");
randList.add("name2");
randList.add("name3");
...
randList.add("name19");
randList.add("name20");
但我的問題是我需要實現List pfff的許多抽象方法。 RandomList不能是抽象的,因爲它不能被實例化。
哪裏是你的名字10000存儲在哪裏? –
它不是真的10000,但它可以是20-100。 他們不存儲,它是硬編碼,如我所示。 –
它們是否存儲在列表中? –