-3

I need to create an array with the following structure:

{int, String, String, int}

I want to insert this array into another array like this:

{int, String, String, int}, {int, String, String, int}, ... and so on.

I have already tried this:

Object[] vector = new Object[100];

public void inserare(int poz, int nr, String nume, String prenume, int nota){

    Object[] aux = new Object[4];
    aux[0] = new Integer(nr);
    aux[1] = new String(nume);
    aux[2] = new String(prenume);
    aux[3] = new Integer(nota);

    vector[poz] = aux;

}

public void afisareLista(){

    for(int i = 0; i < vector.length; i++){
        System.out.println(vector[i]);
    }
}

Aux is inserted, but when I want to print all the elements of main array, all I get is something like this:

[Ljava.lang.Object;@15db9742

Any help for display correctly the elements is appreciated.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
icatalin
  • 1
  • 1
  • 1

2 Answers2

0

Dont do this. Build a class around your int, String, String, int and give them speaking names. Then you can put objects of this class in your array/vector and do not loose any compile type safety.

Skym0sh0
  • 305
  • 3
  • 6
0

Passing an object to System.out.println() results to the invocation of the toString() method on the passed instance. This is an Object and Object's toString() returns the address of the object and not a String containing the field names with their values.

To address this problem :

Either create and use a custom class to contain these 4 fields and populate your array with instances of this class.
Then override toString() in this class to return the expected String.

Or else don't rely on toString() but create a utility method to return a "printable" String of the object and invoke it in the argument of the println() method :

System.out.println(renderMessage(vector[i]));
...
public String renderMessage(Object[] obj){
    return "nr=" + obj[0]+ 
    "nume=" + obj[1]+
    "prenume=" + obj[2]+
    "nota=" + obj[3];
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215