Hi I'm writing a java program in which I need to read the objects added to a Vector random and there should not be repetition. actually I wanted to have a random number by Math.random() * Vector.size() and not to have repetition, keep the random number in an array or something not to read it again next time but guess there must be a method or something for this purpose ... I'll be thankful for any responce
2 Answers
You could generate a sequence from 1 until the size of the vector, shuffle it, then read elements from the vector using those values:
Vector v;
List<Integer> values = new ArrayList<>();
for (int i=0; i < v.size(); ++i) {
values.add(i);
}
Collections.shuffle(values);
// now read the value in the vector using this random sequence
for (int i=0; i < values.size(); ++i) {
System.out.println(vector.get(values.get(i)));
}
Comments
You could simply remove a value from your vector when it was read.
4 Comments
Sarasr
yeah but I need the elements after the procedure :) :(
Lennier
Use a copy of your vector :)
Sarasr
Umm should it be done by vector2 = (Vector) vector 1.clone() ?
Lennier
Yes, you can make a copy by
clone(), or you can make a copy by yourself. But as @Michael said above, Vector is an outdated collection, you better should try to use ArrayList for example.
Vectoris an outdated collection in Java nowadays and you should not be using it unless you have to.ArrayListis preferable.