Multiple array of types

I am working with an array and need some help. I would like to create an array where the first field is a string type and the second field is an integer. For the result:

Console

a  1
b  2
c  3

      

+3


source to share


6 answers


An array can only be of one type. You can create a new class like:

Class Foo{
   String f1;
   Integer f2;
}

Foo[] array=new Foo[10];

      



You might also be interested in using a map (it seems to me that you are trying to map strings to ids).

EDIT: You can also define your array of type Object, but this is what I usually avoid.

+11


source


You can create an array of object type and then when you print to the console you call toString()

each item.

Object[] obj = new Object[]{"a", 1, "b", 2, "c", 3};
for (int i = 0; i < obj.length; i++)
{
    System.out.print(obj[i].toString() + " ");
}

      



Will yield to:

a 1 b 2 c 3

+6


source


Object[] randArray = new Object [3]; 
randArray[0] = new Integer(5);
randArray[1] = "Five";
randArray[2] = new Double(5.0);

for(Object obj : randArray) {
    System.out.println(obj.toString());
}

      

Is this what you are looking for?

0


source


    Object[] myArray = new Object[]{"a", 1, "b", 2 ,"c" , 3};

    for (Object element : myArray) {
        System.out.println(element);
    }

      

0


source


Object [] field = new Object[6];
field[0] = "a";
field[1] = 1;
field[2] = "b";
field[3] = 2;
field[4] = "c";
field[5] = 3;
for (Object o: field)
  System.out.print(o);

      

0


source


try using Vector instead of Array.

-3


source







All Articles