Java 将哈希映射键从字符串转换为int
我有一个HashMap和一个保存键/值的属性文件。 属性文件以“4,5=2”格式存储键/值 我构建了一个从文件中加载属性的方法,它将一对“键/值”放入HashMap数组(字符串、整数)。但我的问题是,我希望键的每个元素都存储为int,以便将它们用作另一个方法的参数。键存储为字符串。 任何帮助都将不胜感激。谢谢大家!Java 将哈希映射键从字符串转换为int,java,Java,我有一个HashMap和一个保存键/值的属性文件。 属性文件以“4,5=2”格式存储键/值 我构建了一个从文件中加载属性的方法,它将一对“键/值”放入HashMap数组(字符串、整数)。但我的问题是,我希望键的每个元素都存储为int,以便将它们用作另一个方法的参数。键存储为字符串。 任何帮助都将不胜感激。谢谢大家! public static HashMap<String, Integer> hashMap = new HashMap<>(); prop.load(in
public static HashMap<String, Integer> hashMap = new HashMap<>();
prop.load(input);
Enumeration<?> e = prop.propertyNames();
while (e.hasMoreElements()) {
key = (String) e.nextElement();
intValue=Integer.parseInt(prop.getProperty(key));
hashMap.put(key, intValue);
publicstatichashmap HashMap=newhashmap();
道具载荷(输入);
枚举e=prop.propertyNames();
而(e.hasMoreElements()){
key=(字符串)e.nextElement();
intValue=Integer.parseInt(prop.getProperty(key));
put(key,intValue);
只需将密钥字符串拆分为“,”
publicstatichashmap HashMap=newhashmap();
道具载荷(输入);
枚举e=prop.propertyNames();
而(e.hasMoreElements()){
字符串sKey=(字符串)e.nextElement();
intValue=Integer.parseInt(prop.getProperty(sKey));
String[]keys=sKey.split(“,”);
用于(字符串键:键)
put(key,intValue);
由于您的键似乎是一对整数,因此需要一个pair类用作键。然后只需访问getFirst()或getSecond()即可与其他api一起使用
public class IntPair {
private final int first;
private final int second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
int hash = 3;
hash = 89 * hash + this.first;
hash = 89 * hash + this.second;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IntPair other = (IntPair) obj;
if (this.first != other.first) {
return false;
}
if (this.second != other.second) {
return false;
}
return true;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
调用另一个方法时进行转换。难道你不能像对值那样简单地将键解析为整数吗???我同意@AlessandroSantini。如果你确实需要
HashMap
,为什么要声明HashMap
?@AlessandroSantini问题是键中没有一个数字。例如,有两个键:“5,6”,我无法将其解析为int。我只能将值解析为int。@VincentDurmont我尝试过它,但也不起作用。密钥对上有两个数字。例如“5,6”“我无法将其解析为int。我会尝试一下,然后告诉您这是否适合我。无论如何,好主意!Key有一对整数,而HashMap存储2个对象。添加值后,将有3个对象,这将导致我出错。”。
public class IntPair {
private final int first;
private final int second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
int hash = 3;
hash = 89 * hash + this.first;
hash = 89 * hash + this.second;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IntPair other = (IntPair) obj;
if (this.first != other.first) {
return false;
}
if (this.second != other.second) {
return false;
}
return true;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}