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
Asked
Active
Viewed 72 times
0
-
1Please post what you have tried. We're not in the habit of just writing your code for you. – Michael Apr 03 '17 at 15:49
-
1Also `Vector` is an outdated collection in Java nowadays and you should not be using it unless you have to. `ArrayList` is preferable. – Michael Apr 03 '17 at 15:51
-
I don't want you to send me a code but wanted to know if there is a Class or some method to read random elements from vector without repetition – Sarasr Apr 03 '17 at 15:53
-
Collections.shuffle(List) – JB Nizet Apr 03 '17 at 15:54
2 Answers
2
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)));
}

Tim Biegeleisen
- 502,043
- 27
- 286
- 360
0
You could simply remove a value from your vector when it was read.

Lennier
- 125
- 1
- 9
-
-
-
-
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. – Lennier Apr 04 '17 at 19:38