Generic Collections

Generic Collections in Java

Java Generic use most classes in java API. since java 1.5 version  uses generics in java collections. Collection, Map and sub types use generics. i have mentioned some example how collections use generics for type safety. more details check java collection class declarations in API.


Collection<String> stringCollection = new ArrayList<String>();

stringCollection can be only added String object. if we add other types of objects, compile error occur.

As we know Collection has implemented the Iterable interface. so we can iterate stringCollection using new for loop as following.

Ex:- List exaple use generics
Collection<String> stringCollection = new ArrayList<String>();
for(String s : stringCollection){
//do something with s
}

Ex:-Set example use generics
Collection<StringBuilder> stringBuilderCollection = new HashSet<StringBuilder>();

for(StringBuilder sb : stringBuilderCollection ){
//do something with sb
}

Ex:-Queue example use generics
Collection<Scanner> queueCollection = new PriorityQueue<Scanner>();

for(Scanner scanner : queueCollection ){
//do something with scanner 
}

Ex:-Map example use generics
Map<String> stringMaps = new HashMap<String>();

for(String s : stringMaps ){
//do something with s 
}









1 comment: