0

I have seen numerous examples for HashMap as well as Hashtable (in java) where they are declared as:

HashMap<KeyType, ValueType> hashmap = new HashMap<KeyType, ValueType>();

or

Hashtable<KeyType, ValueType> hashtable = new Hashtable<KeyType, ValueType>();

However, they are also sometimes declared as:

HashMap hashmap = new HashMap();

or

Hashtable hashtable = new Hashtable();

Same goes for other collections. I always thought that declaration of the type of collection is always a good thing but there are a lot of places where I see them being declared without their types. Can anyone tell which of these methods of declaration is considered proper? Or there is no proper way? What is the difference between these two types of declarations?

Pervy Sage
  • 841
  • 1
  • 10
  • 22
  • Take a look at http://docs.oracle.com/javase/tutorial/java/generics/ – azurefrog Aug 22 '14 at 14:53
  • Adding the types is a help for you because you enable the compiler to check the types at compile time - when you omit the types using *raw* generics, your code may fail at runtime while casting. – Smutje Aug 22 '14 at 14:55
  • @SotiriosDelimanolis - Thanks for pointing to the existing question! The answer there is really helpful. I got introduced to a new term *raw types*. I didn't know they were called so. I am not sure though if I should be deleting my question. – Pervy Sage Aug 22 '14 at 15:10
  • Up to you. If you think it could help anyone, leave it. I do believe it might get deleted automatically in a few days though, if there isn't any activity. – Sotirios Delimanolis Aug 22 '14 at 15:12
  • A lot of Java code was written before generics were introduced to the language, and a lot of people (including myself) feel that generics are more trouble/harm than they're worth. – Hot Licks Aug 22 '14 at 15:26

0 Answers0