Click here to watch in Youtube :https://www.youtube.com/watch?v=d02V7ZmaWnk&list=UUhwKlOVR041tngjerWxVccwCountryInfo.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)