Inside a JVM, Java is "pass-by-reference". The key stored in Hashtable should be the SAME INSTANCE as the one you try to retrieve. The only exception is String and Wrapper which have literal pools. For example, String a = "a"; String b = "a"; (a==b gives you true!), while String c = new String("a"), c is not the same instance of a & b (c==a returns false).
I am not a Java expert, so please bear with me for my silly question-- when constructing hashtable, I passed a String variable to the hashtable as the Key in order to retrieve its value later on. But when retrieving, I am using another String variable -- although the value of the string is same. The hashtable returns no value. For example, for the following table Id value nId 1x a 3x 2x b 3x 3x c 7x the variable ID is the
【在 KG 的大作中提到】 : 看不懂
l*u
6 楼
When you define a new String, avoid to call new String() constructor, try all effort to use literal pool, like this, String a = "my new string";
【在 l*r 的大作中提到】 : I am not a Java expert, so please bear with me for my silly question-- : when constructing hashtable, I passed a String variable to the hashtable as : the Key in order to retrieve its value later on. But when retrieving, I am : using another String variable -- although the value of the string is same. The : hashtable returns no value. : For example, for the following table : Id value nId : 1x a 3x : 2x b 3x : 3x c 7x
t*s
7 楼
if both Id and nId are String variable, then use Id.equal(nID) to judge whether nId's content is the same as Id. Note: don't use Id == nId to do such thing
【在 l*r 的大作中提到】 : I am not a Java expert, so please bear with me for my silly question-- : when constructing hashtable, I passed a String variable to the hashtable as : the Key in order to retrieve its value later on. But when retrieving, I am : using another String variable -- although the value of the string is same. The : hashtable returns no value. : For example, for the following table : Id value nId : 1x a 3x : 2x b 3x : 3x c 7x