Better understand of Generic – Java5

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:screen-shot-2016-10-04-at-7-07-24-pm

Class memeber are show below (Implemented by Generic property):screen-shot-2016-10-04-at-7-09-03-pm

Object inherent:

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:

Screen Shot 2016-10-04 at 7.20.38 PM.png

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:
Screen Shot 2016-10-04 at 7.28.47 PM.png

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.Screen Shot 2016-10-04 at 7.35.55 PM.png

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.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s