hi
i have a problem about Hashtable here,when i compile the following code, a warning prompt that "unchecked call to put(K, V) as a member of the raw type java.util.Hashtable",would you please help me?
code:
...
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "testFactory");
...
btw: what does the the point brackets mean in the following code?
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable {
...
The warning relates to the new generics feature of Java 5.0. The K and V refer to two paremeterized types - one for the key, the other for the value. When using a generic type, you can instantiate these parameters with real types. For example to create a Hashtable that maps String objects to Widget objects you could do the following:
Hashtable<String,Widget> h = new Hashtable<String,Widget>();
h.add("test", new Widget("test"));
Widget w = h.get("test"); // note: no cast needed here
Your code could be changed to the following:
Hashtable<String,String> env = new Hashtable<String,String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "testFactory");
See http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf for Sun's generics tutorial.
To just switch off the warnings, you can use the "-Xlint:-unchecked" option of javac (see http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javac.html).
To switch of generics completely, you can tell javac to treat the code as 1.4 compliant with the "-source 1.4" option.
Many classes in the API have done just that so that they do not have to change the rest of their code. The class Properties used to extend java.util.Hashtable and cast objects (strings) that were being used as property keys and values. Now, they just extended java.util.Hashtable<Object, Object> and kept the type-checking, becuase you you try to save a list of properties with Objects in them, you get Cast exceptions. If the designers has extended java.util.Hashtable<String, String> then this wouldn't be a problem, but I guess they were just being lazy. Feel free to be lazy yourself when recompiling old code, but it would be easier to take advantage of generic types for anything new that your write.
You can't use primitives as keys (or values) in the Collections framework. However, you can make use of autoboxing to achieve the same result with little or no hassle:
Map<Byte, Object> myMap = new HashMap<Byte, Object>();
byte key = 1;
Object value = "Hello World";
// put test
myMap.put(key, value);
// get test
Object getValue = myMap.get(key);