Dimitri
Dimitri

Reputation: 1966

Multidimensional Arrays in Java

Alright, so I've been working with PHP for most of my career and find myself needing to use Java. In my case, the biggest issue I have is creating and manipulating arrays in Java. Example in PHP:

   $cars = array(1 => array("stats"=> array("velocity"=>100,
                                        "acceleration"=>0,
                                        "energy"=>30000,
                                        "distance"=>200
                                      )
                      ),
                 2 => array("stats"=> array("velocity"=>3,
                                        "acceleration"=>6,
                                        "energy"=>30000,
                                        "distance"=>200)
                                      )
                      );

I'm trying to re-create this type of array in Java but I'm having trouble with initializing it. Is the array considered a String in this case? And must the size of the array be set prior to creating it? e.g: String[][][] car = new String[][][]?

Upvotes: 1

Views: 287

Answers (6)

radai
radai

Reputation: 24202

Exactly as aet said in a comment - if you're considering doing this in java - don't. You're doing it wrong.

You should have a class for Car

public class Car {
   private int velocity;
   private int acceleration;
   private int energy;
   private int distance;
   //getters and setters, a constructor that gets all the property values ...
}

and then store your cars in some collection. An ArrayList is the easiest way:

List<Car> cars = new ArrayList<Car>();
cars.add(new Car(100,0,30000,200));
cars.add(new Car(3,6,30000,200));

Accessing the list of cars would then look like this:

cars.get(0).getVelocity(); //collection indexes start at 0

Upvotes: 2

subash
subash

Reputation: 3115

try this..

    Map<Integer, HashMap<String, HashMap<String, Integer>>> map = new HashMap<>();
    HashMap<String, Integer> hm = new HashMap<>();
    hm.put("Velocity", 1);
    hm.put("acceleration", 2);
    HashMap<String, HashMap<String, Integer>> state1 = new HashMap<>();
    state1.put("state1", hm);
    map.put(1, state1);
    System.out.println(map);

Upvotes: 0

Alex
Alex

Reputation: 1008

Yes, lenghts must be provided when initializing an array. Hence, your array would look something like this:

int lenght1=x;
int length2=y;
int lenght3=z;
String[][][] car = new String[lenght1][lenght2][lenght3]

I'm no PHP developer myself, but Classes within the array will obey the OOP rules Java implements in terms of abstraction and inheritance. So when you retrieve the elements you can use their corresponding interfaces whatever the class or interface that contains them are.

On the other hand, if you can't know the array lenghts before the initialization you can use class ArrayList, which is almost like a Vector. This class modify its internal length if new elements are added. Along with ArrayList you have a complete set of data structures in the Java specs to store the elements, like Maps, Sets, Lists, etc...

When instantiating an ArrayList you should specify which class or interface will describe the objects you are storing within the data structure, so you'll have to use generics to instantiate the structure. In your case:

ArrayList<String> dim1=new ArrayList<String>();
ArrayList<ArrayList<String>> dim2=new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<ArrayList<String>>> dim3= new ArrayList<ArrayList<ArrayList<String>>>();

As you can see this structure is way sexier than the simple arrays above, but obviusly will require more care to deal with it. Don't forget to instantiate your arraylists before putting them in your 3d matrix, or you'll get an exception later for accesing a null objects.

Upvotes: 0

rolfl
rolfl

Reputation: 17707

What you have in PHP there would typically be represented as nested Map instances in Java. For example:

HashMap<Integer,Map<String,Map<String,Integer>>> data = new HashMap<>();

Then you could get values (assuming all levels of the Hash are populated correctly) by saying:

int velocity = data.get(1).get("stats").get("velocity");

Populating nested maps like this can be complicated, and you would typically use a helper method to make sure all the 'parent' levels are populated before you add a data member.

Upvotes: 0

kajacx
kajacx

Reputation: 12959

1) is that "stats" index nesserly? if not, you can:

Map<String, Integer>[] cars = new HashMap<String, Integer>[your length here];

this will index your cars by numbers, skip the "stats" index, and allow you to index the last integer by string:

int velocityOfSecondCar = cars[1].get("velocity"); //note indexing from 0

2) if "stats" index is nesserly, you would have to go one dimension deeper

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

I think Java doesn't have TRUE multidimensional arrays. An array which is accessed like a[i][j][k] is simply an array, of arrays, of arrays.

You can try the following construct:

 String[][] car = new String [][] { { "X0", "Y0"},
                                    { "X1", "Y1"},
                                    { "X2", "Y2"},
                                    { "X3", "Y3"},
                                    { "X4", "Y4"} };

Upvotes: 2

Related Questions