Choice of generic container

Generic container, used while not sure incoming parameter type. Two implementation can be used handle this kind of situation. First one is Object container, it sound exactly like it name. Using type <Object> for any incoming parameter as following:

Screen Shot 2017-02-03 at 2.16.23 PM.png

As you may seen,  all member within the class declare as type <Object> so as the constructer. It would work as <Object> is the root class of any object created on Java. So technically it take all type of object however the implementation is limited to member method of class <Object>. Which is inconvenient .

Alright, here is the second approach, generic container.

Screen Shot 2017-02-03 at 2.21.44 PM.png

While adopting this approach, compiler simply assume u know what u doing. Disable all type check and only cast in run-time. It work fin when the type is passed and call in proper way. However some thing weird like “System.out.println” used inside member method but the incoming parameter actually don’t suppose the cast. ClasscastException would be thrown in this case.

As usual the whole example is available on my Github, feel free to check it out and playing around with it, G’day

https://github.com/andykhk/All-About-Java/tree/master/String_Joiner/src/Generic

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s