Generic Map Example:-

  • The MapPlayerRepository class in a given code shows a more practical way to use a generic collection.
  • The program creates a repository of players. It declares a variable (players) of type HashMap<String, String> which stores players based on their position and name.
  • It defines two methods put() and get() to add the elements to the map repository and to retrieve the elements from the map repository respectively.
  1. import java.util.*;
  2. public class MapPlayerRepository
  3. {
  4. HashMap<String, String> players;
  5. public MapPlayerRepository()
  6. {
  7. players = new HashMap<String, String>();
  8. }
  9. public String get(String position)
  10. {
  11. String player = players.get(position);
  12. peturn player;
  13. }
  14. public void put(String position, String name)
  15. {
  16. players.put(players, name);
  17. }
  18. public static void main(String args[])
  19. {
  20. MapPlayerRepository team = new MapPlayerRepository();
  21. team.put(“forward”,”henry”);
  22. team.put(“rightwing”,”ronaldo”);
  23. team.put(“goalkeeper”,”cech”);
  24. System.out.println(“Forward is ” + team.get(“forward”));
  25. System.out.println(“Right wing is ” + team.get(“rightwing”));
  26. System.out.println(“Goalkeeper is ” + team.get(“goalkeeper”));
  27. }
  28. }

Output:-

Forward is henry

Right wing is ronaldo

Goalkeeper is cech

Category Non Generic Class Generic Class
Class declaration public class ArrayList extends AbstractList implements List public class ArrayList<E> extends AbstractList<E> implements List <E>
Constructor declaration public ArrayList (int capacity) public ArrayList (int capacity)
Method declaration public void add(Object o)

public Object get(int index)public void add(E o)

public E get(int index)Variable declaration examplesArrayList list1;

ArrayList list2;ArrayList <String> a3;

ArrayList <Date> a4;Instance declaration exampleslist1 = new ArrayList(10);

list2 = new ArrayList(10);a3 = new ArrayList<String> (10);

a4 = new ArrayList<Date> (10);

  • The major difference is the introduction of the type parameter E. in the following ArrayList declaration and instantiation, the String type substitutes the parametric type variable E.

ArrayList <String> a3 = new ArrayList <String> (10);

  • In the following ArrayList declaration and instantiation, the Date type substitutes the parametric type variable E.

ArrayList <Date> a3 = new ArrayList <Date> (10);

The type variable E in each interface declaration stands for the type of the elements in the collection.

It is common to use upper case letters for type parameters. Java libraries use:

  • E for element type of collection
  • K and V for key value pairs
  • T for all the other types

Wild Card Type Parameters:-

In this we are introduced the wild type parameters.

The Type-Safety Guarantee:-

Examine the code shown given below,

  1. import com.mybank.domain;
  2. import java.util.*;
  3. public class TestTypeSafety
  4. {
  5. public static void main(String args[])
  6. {
  7. List<CheckingAccount> lc = new ArrayList<CheckingAccount>();
  8. lc.add(new CheckingAccount(“Fred”)); // Ok
  9. lc.add(new SavingAccount(“Fred”)); // Compiler error
  10. // therefore…
  11. CheckingAccount ca = lc.get(0); // safe, no cast required
  12. }
  13. }
  • If generic collections mean that inappropriate object types can never be added, then the guarantee is that objects retrieved from the collection can be directly and safely assigned to variables of the same type as the actual type parameter.

The Invariance Challenge:-

Consider the following code,

  1. import com.mybank.domain;
  2. import java.util.*;
  3. public class TestInvariance
  4. {
  5. public static void main(String args[])
  6. {
  7. List<Account> la;
  8. List<CheckingAccount> lc = new ArrayList<CheckingAccount>();
  9. List<SavingAccount> ls = new ArrayList<SavingAccount>();
  10. // if the following were possible…
  11. la = lc;
  12. la.add(new CheckingAccount(“Fred”));
  13. // then the following must also be possible…
  14. la = ls;
  15. la.add(new CheckingAccount(“Fred”));
  16. // so…
  17. SavingAccount sa = ls.get(0); // aarrgghh!
  18. }
  19. }

Java Applet

  • In fact, la = lc; is illegal, so even though a CheckingAccount is an Account, an ArrayList<CheckingAccount> is not an ArrayList<Account>.
  • For the type-safety guarantee always to be valid, it must be impossible to assign a collection of one type to a collection of a different type, even if the second type is a subclass of the first type.
  • This is at odds with traditional polymorphism and would appear at first glance to make generic collections somewhat inflexible.

The Covariance Response:-

Consider the following code,

  1. import com.mybank.domain;
  2. import java.util.*;
  3. public class TestCovariance
  4. {
  5. public static void printNames(List <? Extends Account> lea)
  6. {
  7. for(int i=0; I < lea.size(); i++)
  8. {
  9. System.out.println(lea.get(i).getName());
  10. }
  11. }
  12. public static void main(String args[])
  13. {
  14. List<CheckingAccount> lc = new ArrayList<CheckingAccount>();
  15. List<SavingAccount> lc = new ArrayList<SavingAccount>();
  16. printNames(lc);
  17. printNames(ls);
  18. // but…
  19. List<? Extends Object> leo = lc; // Ok
  20. Leo.add(new CheckingAccount(“Fred”)); // Compiler error
  21. }
  22. }
  • Wildcards allow a degree of flexibility when working with generic collections. The printNames method is declared with an argument that includes a wildcard.
  • The wildcard ‘?’ in List<? Extends Account> may be interpreted as “any kind of unknown elements that are of type Account or a subclass of Account.”
  • The upper bound (Account) means that the elements I the collection can safely be assigned to an Account variable.
  • Thus, the two collections of Account subtypes can both be passed to the printNames method.
  • This covariance response is designed to be read from, rather that be written to. Because of the invariance principle, it is illegal to add to a collection that uses a wildcard with the extends keyword.

Generics: Refactoring Existing Non-Generic Coe:-

  • With generic collections, we can specify generic types without type arguments, which are called raw types. This feature is allowed to provide compatibility with the non-generic code.
  • At compile time, all generic information from the generic code is removed, leaving behind a raw type.
  • This enables interoperability with the legacy code as the class files generated by the generic code and the legacy code would be the same.
  • At run time, an ArrayList<String> and an ArrayList<Integer> het translated into ArrayList, which is a raw type.
  • Using the new Java SE 5.0 or later compiler on older, non-generic code, generates a warning.
  • Below code illustrates a class that generates the compile time warning.
  1. import java.util.*;
  2. public class GenericsWarning
  3. {
  4. public static void main(String args[])
  5. {
  6. List list = new ArrayList();
  7. list.add(0,new Integer(42));
  8. int total = (Integer) list.get(0);
  9. }
  10. }
  • If we compile this GenericsWarning class using the following command:

javac GenericsWarning.java

  • You observe the following warning:

Note: GenericsWarning.java uses unchecked or unsafe operations.

Note: Recompile with –Xlint: unchecked for details.

  • Alternatively, if we compile the class using the following command:

javac –Xlint:unchecked GenericsWarning.java

  • You observe the warning:

GenericsWarning.java:9: warning: [unchecked] unchecked call to add(int, E) as amember of the raw type java.util.List list.add(0,new Integer(42));

  • Although the class compiles fine and the warnings can be ignored, we should heed these warnings and modify our code to be generics-friendly.
  • To resolve this warning in the GenericsWarning class, you need to change line 8 to read:

List<Integer> list = new ArrayList<Integer>();

For more reading about technology news in singapore or from all over the world in all aspect from seo to online marketing do view more about other pages.

Written by Sourabh Bhunje

Sourabh Bhunje, B.E. IT from Pune University. Currently Working at Techliebe. Professional Skills: Programming - Software & Mobile, Web & Graphic Design, Localization, Content Writing, Sub-Titling etc. http://techliebe.com/about-us

Leave a Comment