9

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 type. For result:

Console out

a  1
b  2
c  3
AShelly
  • 34,686
  • 15
  • 91
  • 152
Pirr
  • 113
  • 1
  • 1
  • 6

6 Answers6

20

An array can only have a single 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 like you're trying to map strings to ids).

EDIT: You could also define your array of type Object but that's something i'd usually avoid.

Filip
  • 1,451
  • 1
  • 11
  • 19
10

You could create an array of type object and then when you print to the console you invoke the toString() of each element.

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:

a 1 b 2 c 3

npinti
  • 51,780
  • 5
  • 72
  • 96
1
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're looking for?

Neil
  • 5,762
  • 24
  • 36
1
    Object[] myArray = new Object[]{"a", 1, "b", 2 ,"c" , 3};

    for (Object element : myArray) {
        System.out.println(element);
    }
ollins
  • 1,851
  • 12
  • 16
1
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);
chalimartines
  • 5,603
  • 2
  • 23
  • 33
  • @xmoex: The solution is okay except here the array is being initialized in crude way. – Niraj Nawanit Apr 04 '12 at 09:00
  • this Object[] myArray = new Object[]{"a", 1, "b", 2 ,"c" , 3}; is just syntactic sugar and for this question is my solution fine. – chalimartines Apr 04 '12 at 10:12
  • no offense, but imho I'd consider this bad coding style as it ignores the pairwise occurrence of string and integer per item – xmoex Apr 04 '12 at 10:23
-4

try using Vector instead of Array.

Euclides Mulémbwè
  • 1,677
  • 11
  • 18