Wednesday 8 July 2015

Java : Collection Framework : Collections (UnmodifiableCountryList)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=d02V7ZmaWnk&list=UUhwKlOVR041tngjerWxVccw

CountryInfo.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CountryInfo
{

    List<String> countryList = new ArrayList<String>()
    {
        private static final long serialVersionUID = 1L;

        {
            add("India");
            add("Pakistan");
            add("China");
            add("Iran");
        }
    };

    public List<String> getCountryList(String startingWith)
    {

        if (startingWith == null)
        {
            /*
             * You should always return an emptyList instead of null
             */
            // return null;
            return Collections.emptyList();
        }

        ArrayList<String> filteredCountryList = new ArrayList<String>();
        for (String countryName : countryList)
        {
            if (countryName.startsWith(startingWith))
            {
                filteredCountryList.add(countryName);
            }
        }
        /*
         * Returns an unmodifiable view of the specified list.
         * 
         * If we don't want calling client method to modify the
         * filteredCountryList then we can make unmodifiable like below.
         */
        return Collections.unmodifiableList(filteredCountryList);
    }

}
Client.java
import java.util.List;

/*
 Method: 

 public static <T> List<T> unmodifiableList(List<? extends T> list)

 Parameters:

 list - the list for which an unmodifiable view is to be returned.

 Returns:

 an unmodifiable view of the specified list.

 */

public class Client
{

    public static void main(String[] args)
    {

        CountryInfo countryInfo = new CountryInfo();
        List<String> countryList = countryInfo.getCountryList("I");

        System.out.println("countryList : " + countryList + "\n");

        countryList.add("USA");

    }

}
Output
countryList : [India, Iran]

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
    at Client.main(Client.java:29)
To Download CollectionsDemoUnmodifiableCountryListApp Project Click the below link
https://sites.google.com/site/javaee4321/java-collections/CollectionsDemoUnmodifiableCountryListApp.zip?attredirects=0&d=1

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • No comments:

    Post a Comment