1

I am using Java and I am using a vector 'set' to store data

This is created from a text file as I read each line and store it in an array values[]. Then I have a vector 'set' and for each line I add values[] to the vector 'set' so set looks as shown as above after all the data from the text file is read.

Then the user is given a choice to input the amount of data he wants, for example if he enters 50, half of the vector (the first 7 lines) would be taken by using:

public void pro(int percentage)
{
    int noOfEx = percentage*set.size()/100; 
    root.keptEx = new Vector(set.subList(0, noOfEx));
}

However, I wish that the lines are taken randomly and not after each other but I cannot figure out how to do it with random. Also is there a way how to print out the values of the vector? since

System.out.println(keptEx) 

displays weird symbols not the actual contents.

user4345738
  • 191
  • 9

1 Answers1

0

Shuffle the list of rows:

Collections.shuffle(list);

Then take the first N rows of the shuffled list. Note that calling set what is in fact a list is not a very good idea. Also note that Vector shouldn't be used anymore since Java 2, and we're at Java 8. Use an ArrayList instead. And use generic types, not raw types. These exist since Java 5.

The easiest way to print your list would be to make it contain lists instead of arrays (i.e. you would jave a List<List<Integer>> instead of a List<int[]> (assuming that's what you have). If you want to keep using arrays, then you'll have to loop over each element of your list:

for (int[] row : list) {
    System.out.println(Arrays.toString(row));
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • it is a vector not a list though. I have a lot of code to change everything to an arraylist now :( – user4345738 Jan 03 '15 at 10:15
  • What is written under "All implemented interfaces" here: http://docs.oracle.com/javase/7/docs/api/java/util/Vector.html ? That's why you should always [program to interfaces](http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface). – JB Nizet Jan 03 '15 at 10:17
  • can you give me the equivalent with a vector pls? Since I just need the code to analyse results so the implementation isn't necessarily important – user4345738 Jan 03 '15 at 11:00
  • 1
    Read my comment again, and read the javadoc again. A Vector **is a** List. My solution works fine with a Vector. – JB Nizet Jan 03 '15 at 11:13