When do we need to add content inside <> for Java Collection?

Let me first tell you the meaning of using <>. Whenever we are creating any type of List, Map or Set we use <> with some parameters inside that to define the type of List/Map/Set.

Means like we have 3 Entity Classes one is Country, other one is City and third one is State. Now if we have to create a ArrayList of Country objects, then we can create an object of ArrayList<Country>, that can contain only objects of type Country.

If we are not defining the type of ArrayList and using like ArrayList<> that means this is generic ArrayList and we can add any type of Object. It can be Country, City, State or maybe some other one also.

This one is similar to creating Objects

  1. Object Obj = new Country();
  2. Object obj1 = new State();
  3. State state = new State();
  4. Country country = new Country();

In the above you can can see we are using Object which is generic and we can initialize Object with any type of object (it may be Country, state etc). But in line 3 and line 4 we are defining that we are creating State object and initializing State Entity. Similarly we do it for List, Map or Set by using <> for any type of Object and passing parameter <Country> to restrict to particular Entity.

*We are using 2 parameters in Map because Map works on the basis of Key and value pair and we are defining the type object of Key and type object of Value.

Be the first to comment

Leave a Reply

Your email address will not be published.


*