Reputation: 8959
I have to store data from a UDP packet such as name, address and port number. I originally used 3 array lists to do this but this seems like too much trouble. Instead I thought of using Hashmap for the key - value line up it is but this would mean that the names would be contained in their own hash map or array list.
Is there a good, efficient way of storing all this data in the one collection/container/array?
Upvotes: 0
Views: 82
Reputation: 13841
If you have info from a packet and it's structured, use a custom object: MyPacket. With all the properties you need.
If you need to retrieve that object from a unique key use a Map. By example Map. Then you can save/retrieve each MyPacket using its identifying key (usercode by example, or whatever).
If you need a complex key you should use an own Pojo for the key: Map. Then implement correctly hashCode and equals for that Key class.
If you need some sequencial access you could use TreeMap as an implementation that conserves order. But your key should by Comparable or you must provide a Comparator.
If you have a sequence of items, then consider using a List.
Hope it helps!
Upvotes: 1
Reputation: 236
Try to use something like this :
public class UdpData {
private String name;
private String address;
private int port;
public UdpData(String name, String address, int port) {
super();
this.name = name;
this.address = address;
this.port = port;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
And then use :
List<UdpData> AllData;
Upvotes: 4
Reputation: 168845
Make a POJO with attributes name, address and port number. Add them all to the same collection.
Upvotes: 5
Reputation: 9941
You could use a List
than contains a Map
. Like this:
List<Map<String,String>> container = new ArrayList<Map<String,String>>();
...
Map<String,String> currentEntry = new HashMap<String,String>();
currentEntry.put("name", name);
...
container.add(currentEntry);
Upvotes: 0