views:

122

answers:

4

I have a Vector of Object[] type that stores my data. How to print all it's objects ?

The code:

private static Vector<Object[]> vector = new Vector<Object[]>();


int event=0;
for(int i=0; i<10; i++){
    vector.add( this.addToObject(System.currentTimeMillis(), event , "String") );
    event++;    
}

private Object[] addToObject(long t, int i,String s ){
    Object[] o = new Object[4];
    o[3] = s;
    o[2] = i;
    o[1] = "00000";
    o[0] = t;
    return o;
}

printing

public static void main(String[]args){
    main m = new Main();

    for(int i=0; i< m.vector.size(); i++){

    }

}

And I'd like to get sth like this :

1202393057117 1 OOOOO String
1202393057117 2 OOOOO String
1202393057118 3 OOOOO String
1202393057118 4 OOOOO String
1202393057118 5 OOOOO String

A: 

Inside your printing for loop:

Object[] objs = vector.get(i);
for (Object o : objs) {
    System.out.print(o + " ");
}
System.out.println()
Lauri Lehtinen
A: 
Arrays.deepToString(vector.get(i));

Or print them manually, as Lauri Lehtinen suggests.

Nikita Rybak
A: 

Within the loop:

Object[] o = m.vector.get(i);
System.out.printf("%d %d %s %s\n", o[0], o[2], o[1], o[3]);
Richard Fearn
+2  A: 

Joshua Bloch, in Effective Java, suggests using the for-each loop whenever possible:

for (Object[] array : vector) {
    for (Object obj : array) {
        System.out.println(obj);
    }
}

But since you are using the Object[] with fixed size of 4, with pre-known set of properties, it is highly advisable to create a new class:

class DataHolder {
    private someProperty;
    private someOtherProperty;
    ... + setters and getters
}

And instead of array[2] = something, you will have dataHolder.setSomeProperty(something) - far more readable and maintainable.

The next step is to override toString() (again as advised by Bloch) and implement it to print the whole internal state of the object.

And then the loop will look like this:

for (DataHolder dataHolder : vector) {
    System.out.println(dataHolder);
}
Bozho
For beginners, the for each loop abstracts out important details that people learning the language should know.
jjnguy
they _should_ learn to use the for-each whenever that is possible. The regular for-loop is something trivial and I doubt anyone will have problems with it. Not using for-each, on the other hand, appears to be a problem often.
Bozho
@jjnguy: abstraction is good. It is ignorance that is bad. And no, I don't believe using higher abstraction leads to ignorance.
polygenelubricants
@Bozho: +1, despite the fact that you butchered Bloch's first name. Joshua, not Joshia =)
polygenelubricants
@polygenelubricants fixed that :)
Bozho