Generic, which is a new syntax introduced in Java5. Intend to serve as a alternative way for implementing method and class which adapt multiple type as input argument. Following is the example on Github:
Two types of object are constructed in following stracuture:
Class memeber are show below (Implemented by Generic property):
As you seen above, this a container calss which accept key and value pair in any type. For the generic one, it will adapt any type of object howver it have to be same type as promised upon constructor. On the other hand functionaling on the same way, but it have Object as storing type. Which mean any incoming type is acceptable for key and value. Also the type is able to be alter during the run-time, this its critaical and would be explain later.
Both classes be able to take <String, String> as incoming type and also responsible to print it out by system.out.println( ) method. Print result shown as below:
Yes, it work smoothly. One of the advantage og generic type is it only take promised on setter ( ). It follow the rule strictly so unexpect error won’t happen. As the story keep moving forward, Manager decide to raise the price of Mac Pro . However he/she is not familiar with the class property, hence he set the price as Integer type:
Of course it work smoothly as all type in Java is inherent by Object class, so it won’t cause problem in either Compile nor Run-time.
Noted that the same trick don’t on Generic type, becuase type is fixed upon construction in this example is <String, Stirng> pair. So by the time anyone would decide to feed Integer into a String slot. Error would pop up under compilation time.
In order to let Container class take Integer class for value slot, it need to be declared on constructor.
In conclude, all type check is done on compilation time. No extra cost on run-time and it provide a extra layer for abandoned support type but keeping the flexibility.
- What are the pros and cons of having Generics as erasure or reifiable?