5

I'm from a PHP background, and I'm trying to create a multidimentional array with a difficulty in understanding the Java way of doing things. I thought this could be achieved using JSON and the GSON library, but I'm failing to understand how this is done having followed several tutorials online.

Here is what I'm after in PHP, how can I achieve the same thing in Java?

function creatCars($id) {

    $aCars = array(
        0 => array(
                'name'  => 'vauxhall',
                'doors' => 5,
                'color' => 'black', 
        ),
        1 => array(
                'name'  => 'peogeot',
                'doors' => 3,
                'color' => 'red', 
        ),
    );

    return $aCars[$id];
}

function printFirstCarName($sName) {
    $aCar = createCars(0);
    echo $aCars['name'];
}

//prints "vauxhall"
printFirstCarName();
MinecraftShamrock
  • 3,504
  • 2
  • 25
  • 44
kirgy
  • 1,567
  • 6
  • 23
  • 39
  • Java is a strongly typed language. Heterogeneous data structures can be created but it is a convoluted process. –  Feb 08 '15 at 15:28
  • @Jarrod, you usually do pretty well at finding duplicates; please don't break the pattern. – Shog9 Feb 10 '15 at 19:18

6 Answers6

14

Arrays in PHP are not the same as arrays in Java. Here are the differences:

PHP:

PHP arrays are actually dictionaries. They store a value for each key, where a key can be an integer or a string. If you try to use something else as a key, it will be converted to either an integer or a string.

Java:

Arrays in Java

Java arrays are not associative in the same way as they are in PHP. Let's start with one-dimensional arrays in Java:

A one-dimensional array in Java has a fixed length (that cannot be changed) and each key is an integer in the range of 0 to array.length - 1. So keys, actually called indexes, are always integers. Also, in Java, if you have an array with the keys 2 and 4, you also have (at least) the keys 0, 1 and 3, because the length has to be at least 5 then.

Arrays in Java also have exactly one type and each values in the array can only be of the specified type. Neither size nor type of an array can be changed.

When you create an array in Java, you have two possibilities:

  1. explicitly specify the length when creating the array

    String[] words = new String[4];
    

    The variable words now holds an array of type String with the length a length of 4. The values of all indexes (0 to 3) are initially set to null.

  2. specify elements when creating the array

    String[] words = new String[] {"apple", "banana", "cranberry"};
    

    The variable words now holds an array of type String with a length of 3. The elements contained are as specified with the first element bound to index 0, the second element bound to index 1, and so on.

You can think of multi-dimensional arrays as of an array which holds arrays. A 2-dimensional array could look like this:

String[][] twoD = new String[][] {
 {"apple", "banana", "cranberry"},
 {"car", "ship", "bicycle"}
}

For this twoD[0][2] would be "cranberry" and twoD[1][1] would be "ship". But the number of dimensions of an array does not influence the fact that the keys are integers.

Maps in Java:

Even though Java has no built-in language construct for associative arrays, it offers the interface Map with various implementations, e.g. HashMap. A Map has a type of which the keys are, and a type of which the values are. You can use maps like this:

HashMap<String, String> map = new HashMap<String, String>();
map.put("car", "drive");
map.put("boat", "swim");

System.out.println("You can " + map.get("car") + " a car.");
System.out.println("And a boat can " + map.get("boat") + ".");

This will output:

You can drive a car.
And a boat can swim.

The answer:

The one-to-one way in Java

The answer to your question is that it is not really possible in a reasonable way becasue some of your values are strings, and some are integers. But this would be the most similar code to your PHP array:

//array of HashMaps which have Strings as key and value types
HashMap<String, String>[] cars = new HashMap<String, String>[2];

HashMap<String, String> first = new HashMap<String, String>();
first.put("name", "vauxhall");
first.put("doors", "5");
first.put("color", "black");

HashMap<String, String> second = new HashMap<String, String>();
second.put("name", "peogeot");
second.put("doors", "3");
second.put("color", "red");

//put those two maps into the array of maps
cars[0] = first;
cars[1] = second;

This solution is not very handy, but it is the way that comes closest to your given datastructure.

The cuter way in Java

It seems however, that each of the entries in your PHP array has exactly three properties: name, doors and color. In this case, you may want to create a class Car with these member variables, and store them in an array. This would look like this:

public class Car {

    //member variables
    public String name;
    public int doors;
    public String color;

    //constructor
    public Car(String name, int doors, String color) {
        this.name = name;
        this.doors = doors;
        this.color = color;
    }

}

Now, when you have the class Car, you can create an array of all your cars like this:

Car[] cars = new Car[2];
cars[0] = new Car("vauxhall", 5, "black");
cars[1] = new Car("peogeot", 3, "red");

This is the nicer way to do this in Java.

MinecraftShamrock
  • 3,504
  • 2
  • 25
  • 44
  • 3
    Please feel free to share the reason for your downvote. It will help me improve the answer. – MinecraftShamrock Feb 08 '15 at 16:08
  • 1
    This is great, "The cuter way in Java" is the way I've implemented. Thanks for taking the time for sharing both - its given me a clear understanding. (not sure who is down-voting...all answers have been great and I've up-voted them all) – kirgy Feb 08 '15 at 20:24
0

Instead of creating 2D Array you can create 1 class Car

   public class Car{
    private String carName;
    private String color;
    private int noOfDoors;

    public car(String carName,int door,String color){
    this.carName=carName;
    this.door=door;
    this.color=color;
    }
    public String getCarName(){
    return getCarName;
    }

    public void setCarName(String carName){
    this.carName=carName;
    }
  // Same getters(getXXX) and setters(setXXX) for other Variables
 }

Now create Objects of above class

 Car audi=new Car("audi",2,"Black");
 Car bmw=new Car("bmw",4,"White");

Now add these to the List<Cars>

List<Car> listOfCars=new ArrayList<Car>();
listOfCars.add(audi);
listOfCars.add(bmw);

Now to Print First Car Name

Car firstCar=listOfCars.get(0);
System.out.println(firstCar.getCarName()); //here getter Method Helped you
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
0

I would suggest to get familiar with HashMaps, Maps and ArrayLists. In Java and many other languages is something analogous to a video game cheat.

private static Map<Integer, HashMap<String, String> > carMap = new HashMap<Integer, HashMap<String, String> >();

But in this case you have to understand how would OO principles help you. You can create a class with Car objects and populate a HashMap etc.

   class Car {
     private String name, colour;....
     public Car(){....}
     public void setValues(...){....}
}

To achieve better what you want to I would suggest reading this and getting familiar with some design patterns. It's a bit further down the road, but do it for the lulz and seeing what it's out there. Example : http://howtodoinjava.com/2012/10/23/implementing-factory-design-pattern-in-java/

When moving from scripting to strongly typed languages sometimes you have to change your way of thinking too.

MayTheSchwartzBeWithYou
  • 1,181
  • 1
  • 16
  • 32
0

Firstly you should create class Car i.e:

public class Car {

  enum ColorType {
     BLACK, RED;
  }

  private String name;
  private int doors;
  private ColorType color;

  Car(String name, int doors, ColorType color) {
    this.name = name;
    this.doors = doors;
    this.color = color;
  }

  public String getName() {
    return name;
  }

  public int getDoors() {
    return doors;
  }

  public ColorType getColor() {
    return color;
  }
}

And now you can use arrays but better for you will be use ArrayList:

List<Car> cars = new ArrayList<Car>();
cars.add(new Car("vauxhall", 5, BLACK));
cars.add(new Car("peogeot", 3, RED));

for (Car car : cars ) {
  System.out.println("Car name is: " + car.getName());
}
czerpak
  • 11
  • 1
-1

It seems what you are trying to achive is an 'array of cars'. So instead of creating an array of arrays, I recommend to literally implement an 'array of cars'.

To do this, I would define the car first, possibly in a different file:

class Car {
  //you can make these private and use 'get' and 'set' methods instead
  public String name;
  public String color;
  public int doors;

  public Car() {
    name = "";
    color = "";
    doors = 0;
  }

  public Car(String name, String color, int doors) {
    this.name = name;
    this.color = color;
    this.doors = doors;
  }
}

You can use the car structure in an another module like this:

Car[] cars = new Car[100]; //create one hundred cars
cars[11].doors = 4; //make the 12th car's number of doors to 4 

You can use more flexible data structures, like Vectors, List, Maps, etc... Search for Java collections, you will find tones of info.

Gábor
  • 324
  • 2
  • 6
  • Classes don't make much sense with no methods and all their fields being public. – gvlasov Feb 08 '15 at 15:50
  • This code would actually throw a NullPointerException because all array elements are initially null – MinecraftShamrock Feb 08 '15 at 18:49
  • I know that, I just wanted focus on the approach: defining a type for car, and then use collections. I'll fix up the code. – Gábor Feb 09 '15 at 11:38
  • Also, if there is no real behavior, and the type feels more like a data structure, then I see no problem with public data fields. – Gábor Feb 09 '15 at 11:46
-2

Java is not a loosely typed language, you have to tell the compiler what each variable is going to be. And to store this kind of structured data in Java, you should first declare a class and instantiate objects of that class. Following is how you would achieve the same thing as your PHP code:

class Car {
    private String name, color;
    private int doors;

    Car(String name, int doors, String color) {
        this.name = name;
        this.doors = doors;
        this.color = color;
    }

    public String getName() {
        return this.name;
    }
}

public class CarMainClass {
    public static void main(String[] args) {
        Car[] aCars = new Car[2];

        aCars[0] = new Car("vauxhall", 5, "black");
        aCars[1] = new Car("peogeot", 3, "red");

        System.out.println("First car name is: " + aCars[0].getName());
    }
}

Compile using:

javac CarMainClass.java

Then run:

java CarMainClass

You will have to learn the basics of Java first to understand the above code.

Ananth
  • 4,227
  • 2
  • 20
  • 26