我目前的项目要求我为各种用例使用一对字符串。我目前正在使用Apache Lang3 Pair元组来处理这种情况。当前的实现如下所示
private List<Pair<String, String>> configParameters;
private List<Pair<String, String>> sensorReadingMeasures;
在与团队的其他成员讨论后,我们决定,因为我们需要公开这些字符串对,所以最好找到本机Java解决方案。
我试图在java util库中使用AbstractMap找到一个解决方案,但我没有太多运气能够实例化它,谷歌搜索没有提供太多关于帮助我的信息。
我试图通过这样做重建上述内容,
AbstractMap<String, String> pair = new AbstractMap<String, String>();
我可以使用keyset()函数提取所需信息,并通过get()函数为每个键值提取所需信息。
除了我的实例化问题,这似乎是一种非常低效的方法来获得相同的功能,我很好奇是否有更好的选择。如果没有,请提供一个关于如何适当地实例化AbstractMap的示例。
答案 0 :(得分:2)
如果每对中的两个字符串中的一个是唯一的,因为您建议使用AbstractMap
似乎建议,您可能希望公开返回Map<String,String>
的API,并使用您对该界面的选择(例如,LinkedHashMap<String,String>
)。
您班级的用户可以使用String
从Map
中提取Map.Entry<String,String>
对,而不是为每个密钥调用get
:
Map<String,String> getAllPairs() {
...
}
...
for (Map.Entry<String,String> pair : myClass.getAllPairs()) {
// You can use pair.getKey() and pair.getValue() here
}
答案 1 :(得分:0)
你能不能只使用POJO:
public class Tuple {
public String oneString;
public String otherString;
}
你可以列出它们:
public List<Tuple> tuples = new ArrayList<Tuple>();
如果您:
,您可以拥有Collection
个可以搜索到的@Override
public boolean equals(Object obj) {
// Code to handle non-Tuples and null goes here
// Code to handle null oneString values goes here (if you allow that)
return ((Tuple)that).oneString.equals(oneString);
}
@Override
public int hashCode() {
// handle null oneString values here
return oneString.hashCode();
}
个
{{1}}