Eric Lee
Eric Lee

Reputation: 710

How to make 3 dimensional array in java?

I have a query string like

"1_timestamp=201612312&1_user=123&2_timestamp=20145333&2_user=5432";

But I want to make them in array like below.

array(
    0 => (
        timestamp = 201612312,
        user = 123,
        ),
    1 => (
        timestamp = 201612312,
        user = 123,
        ),
);

I'm sorry to show you php type of array though I'm new to java.

How do I make it something like that?

Thank you

Upvotes: 0

Views: 495

Answers (2)

apadana
apadana

Reputation: 14620

This is the closest structure to what you are doing in php, and if your data has more fields it can be easily added to the Data class:

import java.util.ArrayList;
import java.util.List;

class Data {
    int timestamp;
    int user;

    Data(int ts, int user) {
        this.timestamp = ts;
        this.user = user;
    }
}

public class Test {

    public static void main(String[] args) {
        List<Data> data = new ArrayList<Data>();
        Data d1 = new Data(201612312, 123);
        Data d2 = new Data(201612312, 123);
        data.add(d1);
        data.add(d2);

        System.out.println(data.get(1).user);
    }
}

Upvotes: 2

ooozguuur
ooozguuur

Reputation: 3466

You can do it without writing a class. You can use it like this.

Map<String, String> map1 = new HashMap<String, String>();
map1.put("1_timestamp", "201612312");
map1.put("1_user", "123");

Map<String, String> map2 = new HashMap<String, String>();
map2.put("2_timestamp", "20145333");
map2.put("2_user", "5432");

List<Map<String,String> mapList = new ArrayList<Map<String, String>>();
mapList.add(map1);
mapList.add(map2);

for (Map<String, String> map : list) {
    for (Map.Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " - " + entry.getValue());
    }
}

Upvotes: 1

Related Questions