Java Hashtable : 一个键 - 两个值,如何得到它们?
Java Hashtable : one key - two value, how to get both of them?
我的问题是我有一个哈希表,最后我得到了一些具有两个值的键。我想得到这两个值,所以我可以看到我想要哪个并接受它。
这里有一个例子:
Hashtable<String, String> myTable = new Hashtable<>();
myTable.put("key1", "value1");
myTable.put("key1", "value2");
System.out.println(myTable.get("key1"));
//output : value2
如何获取这两个值?
感谢您的帮助!
编辑:
在我的测试中,HashTable 不能像这样存储 2 个值,但我保证在我的项目中我有一个(我相信)做同样事情的代码。当我的算法有 运行 I System.out.prinln(myTable) 时,它确实多次显示具有不同值的相同键。
在 HashMap class 中,put 函数在对象不存在时添加对象,如果对象存在则只更新值。您可以创建另一个 class 来保留值;
class exampleValue {
String v1, v2;
exampleValue() {}
}
和
HashMap<String, exampleValue> h = new HashMap<>();
exampleValue v = new exampleValue();
v.v1 = "a";
v.v2 = "b";
h.put("key", v);
h.get("key").v1; //returns "a"
h.get("key").v2; //returns "b"
这取决于创建哈希表的方式,在您的示例中。您创建一个 HashTable 将一个 String 映射到一个 String,然后因为该值是一个 String,您不能指望 table 可以在一个键上存储多个值。当您执行第二个 put
方法时,它将找到值为 key1
的键并将映射到该键的先前值替换为新值。
如果您想在一个键上存储多个值,请考虑为您的键保存多个值的列表。下面是一个将字符串类型的键映射到多个字符串值的示例:
Hashtable<String, ArrayList<String>> myTable = new Hashtable<>();
ArrayList<String> listValue = new ArrayList<>();
listValue.add("value1");
listValue.add("value2");
myTable.put("key1", listValue);
System.out.println(myTable.get("key1")); // get all values of the key [value1, value2]
System.out.println(myTable.get("key1").get(0)); // get the first value of this key, value1
System.out.println(myTable.get("key1").get(1)); // get the second value of this key, value2
建议使用 HashMap 而不是 HashTable。
我的问题是我有一个哈希表,最后我得到了一些具有两个值的键。我想得到这两个值,所以我可以看到我想要哪个并接受它。
这里有一个例子:
Hashtable<String, String> myTable = new Hashtable<>();
myTable.put("key1", "value1");
myTable.put("key1", "value2");
System.out.println(myTable.get("key1"));
//output : value2
如何获取这两个值?
感谢您的帮助!
编辑: 在我的测试中,HashTable 不能像这样存储 2 个值,但我保证在我的项目中我有一个(我相信)做同样事情的代码。当我的算法有 运行 I System.out.prinln(myTable) 时,它确实多次显示具有不同值的相同键。
在 HashMap class 中,put 函数在对象不存在时添加对象,如果对象存在则只更新值。您可以创建另一个 class 来保留值;
class exampleValue {
String v1, v2;
exampleValue() {}
}
和
HashMap<String, exampleValue> h = new HashMap<>();
exampleValue v = new exampleValue();
v.v1 = "a";
v.v2 = "b";
h.put("key", v);
h.get("key").v1; //returns "a"
h.get("key").v2; //returns "b"
这取决于创建哈希表的方式,在您的示例中。您创建一个 HashTable 将一个 String 映射到一个 String,然后因为该值是一个 String,您不能指望 table 可以在一个键上存储多个值。当您执行第二个 put
方法时,它将找到值为 key1
的键并将映射到该键的先前值替换为新值。
如果您想在一个键上存储多个值,请考虑为您的键保存多个值的列表。下面是一个将字符串类型的键映射到多个字符串值的示例:
Hashtable<String, ArrayList<String>> myTable = new Hashtable<>();
ArrayList<String> listValue = new ArrayList<>();
listValue.add("value1");
listValue.add("value2");
myTable.put("key1", listValue);
System.out.println(myTable.get("key1")); // get all values of the key [value1, value2]
System.out.println(myTable.get("key1").get(0)); // get the first value of this key, value1
System.out.println(myTable.get("key1").get(1)); // get the second value of this key, value2
建议使用 HashMap 而不是 HashTable。