I'm using arraylist in java and I need to add integers during 10 iterations (integer is got randomly from an array of integers named arrint) without any repetition:
for (int i =0; i<10; ++i)
array.add(integer);
and then add in the same array 20 other integers for the same array of integer(arrint) during 20 iteration without repetition
for (int i =0; i<10; ++i)
array.add(integer);
but repetition is permitted between the 10 first integers and the 20 integers.
thank you
Set, rather than List, prevents duplicates. So you could establish a Set<Integer> and after populating it, add all of its elements to the List (with list.addAll(set)). Then clear the Set and repeat for the next 20.
It's not clear from your description what you want to happen if duplicates are encountered. Do you want to add items into the Set until it contains 10, just discarding duplicates? Or do you want to throw an exception if a duplicate is encountered?
public class Foo {
private final Random random = new Random();
public List<Integer> createList() {
// Create empty list to store results.
List<Integer> ret = new ArrayList<Integer>(30);
// Add 10 randomly generated integers.
ret.addAll(createRandomIntegers(10));
// Add another 20 randomly generated integers which could potentially
// contain integers already added previously (the OP states that this is ok).
ret.addAll(createRandomIntegers(20));
return ret;
}
/**
* Utility function that creates a set of randomly generated
* integers of specified size. We use a Set to avoid duplicates.
*/
protected Set<Integer> createRandomIntegers(int sz) {
Set<Integer> ret = new HashSet<Integer>();
while (ret.size() < sz) {
ret.add(random.nextInt());
}
return ret;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With