0

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

4
  • 1
    Please post what you have tried. We're not in the habit of just writing your code for you. Commented Apr 3, 2017 at 15:49
  • 1
    Also Vector is an outdated collection in Java nowadays and you should not be using it unless you have to. ArrayList is preferable. Commented Apr 3, 2017 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 Commented Apr 3, 2017 at 15:53
  • Collections.shuffle(List) Commented Apr 3, 2017 at 15:54

2 Answers 2

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)));
}
Sign up to request clarification or add additional context in comments.

Comments

0

You could simply remove a value from your vector when it was read.

4 Comments

yeah but I need the elements after the procedure :) :(
Use a copy of your vector :)
Umm should it be done by vector2 = (Vector) vector 1.clone() ?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.