Dev01
Dev01

Reputation: 4222

Java: Data type similar to javascript object?

In java, is there any data type similar to javascript object type where I can store stuff something like we do in javascript.

Here is an object and it contains three arrays inside:

var myObject = {"smsBody": [], "totalSMS": [], "sender": []};

I can push data to individual array items inside that object:

myObject.totalSMS.push("5");
myObject.totalSMS.push("10");

And then can loop over them to get whole data out of an array item:

for (var i = 0; i < myObject.totalSMS.length; i++) {
  alert(myObject.totalSMS[i]);
}

Is there something similar in Java plz?

Upvotes: 0

Views: 122

Answers (2)

andersschuller
andersschuller

Reputation: 13907

This is about as close as you can get in Java to the code you posted:

Map<String, List<String>> myObject = new HashMap<>();
myObject.put("smsBody", new ArrayList<>());
myObject.put("totalSMS", new ArrayList<>());
myObject.put("sender", new ArrayList<>());

List<String> totalSMS = myObject.get("totalSMS");
totalSMS.add("5");
totalSMS.add("10");

for (String s : totalSMS) {
    System.out.println(s);
}

Note there are quite a few little differences, like the fact that you cannot use something like myObject.totalSMS, but rather need to use the String "totalSMS" as the key of a Map. Java also has a more convenient for-each loop, which means you don't need to iterate over the indices of the elements and access them separately (although you can still loop over a list by the element indices if you want).

Upvotes: 1

Excelsior
Excelsior

Reputation: 51

What you have described can be described as an array of arrays in java. You could use a collection such as ArrayList to make it more dynamic. If you are looking for something more general to store different types of elements, you should consider using an inner class.

To refer to your example, the code in JAVA would be (providing all of the arrays contain only integers):

 ArrayList<ArrayList<Integer>> myObject = new ArrayList<ArrayList<Integer>>();
    myObject.add(new ArrayList<Integer>());
    myObject.add(new ArrayList<Integer>());
    myObject.add(new ArrayList<Integer>());

    myObject.get(0).add(5);
    myObject.get(0).add(10);

    for (Integer i : myObject.get(0))
     System.out.println(i);

If you would like to name the Collections you could use an Map:

 Map<String,ArrayList<Integer>> myObject = new HashMap<String,ArrayList<Integer>>();
    myObject.put("smsBody",new ArrayList<Integer>());
    myObject.put("totalSms",new ArrayList<Integer>());
    myObject.put("sender",new ArrayList<Integer>());

    myObject.get("totalSms").add(5);
    myObject.get("totalSms").add(10);

    for (Integer i : myObject.get("totalSms"))
     System.out.println(i);

Upvotes: 1

Related Questions