Monday, January 12, 2015

Java Collections Program



Write  for Collections.checkedSet() method

package com.java2novice.collections;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class MyCheckedSet
{
public static void main(String a[])
{
         
        Set mySet = new HashSet();
        mySet.add("one");
        mySet.add("two");
        mySet.add("three");
        mySet.add("four");
        Set chkSet = Collections.checkedSet(mySet, String.class);
        System.out.println("Checked set content: "+chkSet);
        mySet.add(10);
        chkSet.add(10);
    }
}

Write  for Collections.checkedMap() method

package com.java2novice.collections;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class MyCheckedMap
{
public static void main(String a[])
{
        Map myMap = new HashMap();
        myMap.put("one", 1);
        myMap.put("two", 2);
        myMap.put("three", 3);
        myMap.put("four", 4);
        Map chkMap = Collections.checkedMap(myMap, String.class, Integer.class);
        System.out.println("Checked map content: "+chkMap);
        myMap.put(10, "ten");
       chkMap.put(10, "ten"); //throws ClassCastException
    }
}

How to check there in no common element between two list objects by using Collections.disjoint() method

package com.java2novice.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyListDisjoint
{
public static void main(String a[])
{
        List sl = new ArrayList();
        sl.add("apple");
        sl.add("java");
        sl.add("c++");
        sl.add("unix");
        sl.add("orange");
        sl.add("airtel");
        List tl = new ArrayList();
        tl.add("job");
        tl.add("oracle");
        tl.add("jungle");
        tl.add("cricket");
        boolean isCommon = Collections.disjoint(sl,tl);
        System.out.println("Does not found any common elements? "+isCommon);
        tl.add("java");
        isCommon = Collections.disjoint(sl,tl);
        System.out.println("Does not found any common elements? "+isCommon);
    }
}

No comments:

Post a Comment