我有这个Ruby结构:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("extra_data");
// do something with the result
} else if (resultCode == Activity.RESULT_CANCELED) {
// some stuff that will happen if there's no result
}
}
}
我可以使用哪种数据结构来形成相同的结构并根据所需的键找到合适的值?我尝试过使用Gualava:
COUNTRIES = {
'AF' => { :country => 'Afghanistan', :alpha => 'AFG', :number => '004' },
'AT' => { :country => 'Austria', :alpha => 'AUT', :number => '040' }
}
但是如何映射主键Table<String, String, Integer> table = HashBasedTable.create();
table.put("Austria", "AUT", 040);
?也许在Table中使用Hashmap?但是然后我如何使用一些内键从Hashmap获取值>
答案 0 :(得分:2)
您可以编写自己的课程。 (也有构造函数+ Getter / Setter)
public class Country {
private String country;
private String alpha;
private String number;
}
要存储我们班级的对象,可以使用地图。
Map<String, Country> table = new HashMap<>();
table.put("AF", new Country("Afghanistan", "AFG", "004");
table.put("AT", new Country("Austria", "AUT", "040");
答案 1 :(得分:2)
用Java编写的惯用方式如下:
public class Country {
private final String country;
private final String alpha;
private final String number;
// constructor and getters
}
Map<String, Country> map = new HashMap<>();
COUNTRIES.put("AT", new Country("Austria", "AUT", "040");
// etcetera
我个人将2个字母代码作为Country
的额外字段包括在内:
它允许您创建辅助哈希表;例如启用按3个字母的国家/地区代码查找。例如:
Map<String, Country> map2 = new HashMap<>();
for (Country country: map.values()) {
map2.put(country.getAlpha(), country);
}
// That could also be written as:
// Map<String, Country> map2 = map.values().stream()
// .collect(Collectors.toMap(Country::getAlpha, Function.identity())
map2.get("AUT");
可以使用Map<String, Map<String, String>>
来实现此功能,但是它更麻烦,效率更低且更脆弱。 1 。
1-如果构建地图或随后访问的代码中有错字,就会出现问题。例如,如果您在其中一个映射条目中未键入“国家”作为“国家/地区”,则编译器不会选择它,并且您可能会获得意外的NPE。