[英]How do I setup a map for a unique identifier?
We have an database table and the unique index on that table is a composite key (String, int, int). 我们有一个数据库表,该表上的唯一索引是一个复合键(String,int,int)。 I want to add a field in my Java class that will hold this key. 我想在我的Java类中添加一个包含该键的字段。 I tried: 我试过了:
Map<String, Integer, Integer>
but the IDE told me I cannot do that as a map is just Map K,V. 但是IDE告诉我我不能这样做,因为地图只是Map K,V。
My question is what is the best way to represent this key? 我的问题是代表此密钥的最佳方法是什么?
Map<String, Integer, Integer>
That does not work, because Map
takes only two type parameters (for the key and the value), not three. 那是行不通的,因为Map
仅接受两个类型参数(用于键和值),而不是三个。
Create a class that represents the key. 创建一个代表密钥的类。 Use that as a key in the map. 将其用作地图中的键。 Note: The key class must implement the hashCode
and equals
methods correctly. 注意:密钥类必须正确实现hashCode
和equals
方法。
Why don't you just create a custom key like this - 您为什么不像这样创建自定义密钥-
class MyKey{
int key1;
int key2;
String key3;
// override hashCode & equals
}
You can then use this class as your key 然后,您可以使用此类作为密钥
Map<MyKey, Value>
It depends what you want to do with it: 这取决于您要如何处理:
You can create a bean as key: 您可以创建一个bean作为键:
public class MyCompositeKey {
private String field1;
private Integer field2, field3;
//getters and setters here
@Override
public int hashCode() {
//your implementation here, you can use here the hashCode of Integer and String
}
@Override
public boolean equals(Object o) {
if (o instanceof MyCompositeKey) {
MyCompositeKey that=(MyCompositeKey) o;
//compare here the fields
}
return false;
}
}
Or you can do something like: 或者,您可以执行以下操作:
String key=field1+"-"+field2+"-"+field3;
and use that String as key in your map. 并将该字符串用作地图中的键。
Or maybe you just need a List<Comparable>
where you add the three elements in a prefixed order. 或者,也许您只需要一个List<Comparable>
在其中按前缀顺序添加三个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.