Reputation: 41605
This might be a very basic question but I'm not used to work with Java and I would like to create an array / list like this:
6546:{
"Ram":{
24M,
4M,
64M,
...
},
"Cpu":{
2%,
4%,
6%,
...
},
...
}
I've been trying it with LinkedList
and so on but end up creating lists of lists and it starts looking very ugly.
This is a very common array in JSON, PHP or even Javascript, what would be the best way to create it by using Java?
Upvotes: 0
Views: 87
Reputation: 901
This looks more like a key/value indexed structure.
One way (of many) to do something equivalent in Java:
Map<Integer, Map<String, String[]>> myData = new Hashtable<Integer, Map<String, String[]>>();
Map<String, String[]> entries = new Hashtable<String, String[]>();
entries.put("Ram", new String[] {"24M", "4M"}); // etc.
entries.put("Cpu", new String[] {"2%", "4%"}); // etc.
myData.put(6546, entries);
This would create an equivalent data structure, and you could index into it in a familiar fashion:
myData.get(6546).get("Ram")[0];
Although that would be VERY bad form, as you should always check for nulls before using the results of .get(x)
, such as:
Map<String, String[]> gotEntry = myData.get(6546);
if (gotEntry != null) {
String[] dataPoints = gotEntry.get("Ram");
if (dataPoints != null && dataPoints.length > 0) {
String data = dataPoints[0];
}
}
And so on. Hope this helps!
One other more interesting option is to use something like described here where you can define your data as a JSON string, and convert it into Object types later using un/marshalling.
Upvotes: 0
Reputation: 23945
HashMap<Integer, HashMap<String, List<Object>>>
looks good.
Upvotes: 0
Reputation: 3694
It might be done in that way.
int[][] twoDimTable = new int[size][size];
String[][] twoDimTable = new String[size][size];
or
List<List<Integer> list = new ArrayList<>(); //or
List<List<String> list = new ArrayList<>();
Upvotes: 0
Reputation: 60848
You want a List<List<Integer>>
or an int[][]
.
List<List<Integer>> list = new ArrayList<>();
list.add(new ArrayList<>());
list.get(0).add(24);
But perhaps you just want to use something like Gson
and store this as JSON.
Or create a class like:
class Data {
private final List<Integer> ram = new ArrayList<>();
private final List<Integer> cpu = new ArrayList<>();
}
Or if you want to avoid creating classes? (Which you shouldn't)
Map<String, List<Integer>> map = new HashMap<>();
map.put("cpu", new ArrayList<>());
map.put("ram", new ArrayList<>());
Upvotes: 1