简体   繁体   English

不确定如何存储数据

[英]unsure about how to store data

I have to store data from a UDP packet such as name, address and port number. 我必须存储来自UDP数据包的数据,例如名称,地址和端口号。 I originally used 3 array lists to do this but this seems like too much trouble. 我最初使用3个数组列表来执行此操作,但这似乎太麻烦了。 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. 取而代之的是,我想到了使用Hashmap作为键-值列表,但这意味着名称将包含在其自己的哈希图或数组列表中。

Is there a good, efficient way of storing all this data in the one collection/container/array? 是否有一种良好,有效的方式将所有这些数据存储在一个集合/容器/阵列中?

Make a POJO with attributes name, address and port number. 用属性名称,地址和端口号创建一个POJO。 Add them all to the same collection. 将它们全部添加到同一集合中。

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;

If you have info from a packet and it's structured, use a custom object: MyPacket. 如果您有数据包中的信息并且结构化,请使用自定义对象: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). 然后,您可以使用其标识密钥(例如,用户代码或其他方式)保存/检索每个MyPacket。

If you need a complex key you should use an own Pojo for the key: Map. 如果需要复杂的键,则应使用自己的Pojo作为键:Map。 Then implement correctly hashCode and equals for that Key class. 然后正确实现hashCode并等于该Key类的值。

If you need some sequencial access you could use TreeMap as an implementation that conserves order. 如果需要顺序访问,可以将TreeMap用作节省顺序的实现。 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! 希望能帮助到你!

You could use a List than contains a Map . 您可以使用List而不包含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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM