Home  >  Core Java

Example of Collections Checked Method in Java

By Arvind Rai, May 26, 2013
In Java, generics helps to avoid insertion of wrong type at compile time. But generics do not guarantee at run time to avoid insertion of wrong type. In collection we have checked methods that will return the dynamically typesafe view for the given collection. These methods are like Collections.checkedCollection, Collections.checkedList, Collections.checkedMap, Collections.checkedSet etc. These methods return a view of the given collection in which no wrong type object can be inserted. Find the use in the below example.
CollectionsCheckedDemo.java
package com.concretepage.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class CollectionsCheckedDemo {
    public static void main(String[] args) {
        Person a1 = new Person("A");
        Person a2 = new Person("B");
        Person a3 = new Person("C");
        List<Person> list = new ArrayList<Person>();
        list.add(a1);
        list.add(a2);
        list.add(a3);
        Collection<Person> checkedCon = Collections.checkedCollection(list, Person.class);
        
        Collection<Person> checkedList = Collections.checkedList(list, Person.class);
        
        Map<Integer,Person> map = new HashMap<Integer,Person>();
        map.put(1,a1);
        map.put(2,a1);
        map.put(3,a1);
        Map<Integer,Person> checkedMap = Collections.checkedMap(map, Integer.class, Person.class);
        
        Set<Person> set = new HashSet<Person>();
        set.add(a1);
        set.add(a2);
        set.add(a3);
        Set<Person> checkedSet = Collections.checkedSet(set,Person.class);
    }
}
class Person {
        private String name;
        public Person(String name) {
                this.name = name;
        }
	public String getName() {
		return name;
	}
}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us