Reputation: 336
Can a multidimensional array in java have two types like a string and double in it?
Like: {name, num},{name, num}
Upvotes: 1
Views: 246
Reputation: 611
This solution has nothing to do with arrays, but if you've got {name, num}, {name, num}
data, you might want to consider using a map.
Map<String, Double> map = new HashMap<String, Double>();
Double valueX = 123.456;
Double valueY = 654.321;
map.put("nameX", valueX);
map.put("nameY", valueY);
Double valueX = c.get("name");
for(String name:c.keySet()) {
System.out.println("name:"+name+"\tvalue:"+c.get(name));
}
Upvotes: 0
Reputation: 3559
In Java, this is normally done with a class.
class C {
public String name;
public int num;
}
(later)
C[] myArray = new C[5];
myArray[3] = new C();
myArray[3].name = "Ford";
myArray[3].num = 42;
name and num should typically be made private and accessed with getters and setters, but this is beyond the point.
Upvotes: 2
Reputation: 77
int row=10;
int col=10;
Object [][] objArray=new Object[row][col];
objArray[0][0]=181818;
objArray[0][1]="Hello String";
System.out.println(objArray[0][0]);
System.out.println(objArray[0][1]);
You can use Object for that.
Plus you need to search before you post it. There is already answer here. Two-dimensional array of different types
Upvotes: 0
Reputation: 7812
Zoyd has it right, that this should be done with a class. Here's a more complete example.
class MyClass
{
private String name;
private int num;
public MyClass(String name, int num)
{
this.name = name;
this.num = num;
}
public String getName()
{
return name;
}
public int getNum()
{
return num;
}
}
MyClass[] array = new MyClass[5];
array[0] = new MyClass("name1", 5);
array[1] = new MyClass("name2", 8);
...
If name or num ever need to change after original creation, then you can add setters for them.
Upvotes: 2