3. Methods can be defined to operate on unknown types of Objects without using ‘Objects’ class. And no type casting is required.
4. Big advantage: collections are now type safe.2 Example : ‘Generify ‘ your Java classes – public class Box<T> { private T t ; public void add(Tt ) { this.t = t; } public T get() { return t; } } How to use this : Box<Integer> integerBox = new Box<Integer>(); … integerBox.add(new Integer(25)); //typesafe only Integers can be passed Integer myInt = integerBox.get() //no typecasting required T is a type parameter that will be replaced by a real type. T is the name of a type parameter. This name is used as a placeholder for the actual type that will be passed to Gen when an object is created.
5. Generics – Example 2 3 Another Example public class GenericFactory<E> { Class theClass = null; public GenericFactory(Class theClass) { this.theClass = theClass; } public E createInstance() throws …{ return (E) this.theClass.newInstance(); } Usage : Creates a Factory of Generic Type GenericFactory<MyClass> factory = new GenericFactory<MyClass>(MyClass.class); MyClass myClassInstance = factory.createInstance();
6. Generics – Generics in Methods 4 static <T> void fromArrayToCollection(T[] a, Collection<T> c) { for (T o : a) { c.add(o); } } static <T> Collection<T> fromArrayToCollectionv2(T[] a) { Collection<T> c = new ArrayList<T>(); for (T o : a) { c.add(o); } return c ; } One more Interesting Example… public <T> T ifThenElse(boolean b, T first, T second) { return b ? first : second; }
7. Generics – With Collections 5 Lists List<String> list = new ArrayList<String>(); list.add(“A String”); String string2 = list.get(0); // no type casting. Maps (can define multiple typed parameters) Map<String, String> map = new HashMap<String, String>();map.put ("key1", "value1");map.put ("key2", "value2");String value1 = map.get("key1"); Iterating a Generic List: List<String> list = new ArrayList<String>(); Iterator<String> iterator = list.iterator(); while(iterator.hasNext()){ String aString = iterator.next(); } Backward Compatibility List list = new ArrayList<String>(); Nested Generic Types List<List<String>> myListOfListsOfStrings;
8. Generics – Diving Deeper 6 Generics and Subtyping List<String> ls = new ArrayList<String>(); List<Object> lo = ls; //illegal won’t compile!! What’s the Problem ? lo.add(new Object()); String s = ls.get(0); // attempts to assign an Object to a String! In other words Collection<Object> is not a supertype of all the types of collections To cope with this sort of situation use Wildcards static void printCollection2(Collection<?> c) { // Collection<?> -“collection of unknown” for (Object e : c) { System.out.println(e); } } Limitation in using unbounded wildcard Any method that takes Generic type of argument cannot be invoked : Collection<?> c = new ArrayList<String>(); c.add(new Object()); // compile time error
9.
10. A wildcard with a lower bound looks like " ? super Type " Example : public class Collections { public static <T> void copy ( List<? super T> dest, List<? extends T> src) { // uses bounded wildcards for (int i=0; i<src.size(); i++) dest.set(i,src.get(i)); } } List<Object> output = new ArrayList< Object >(); List<Long> input = new ArrayList< Long >(); ... Collections.copy(output,input); // fine List<String> output = new ArrayList< String >(); List<Long> input = new ArrayList< Long >(); ... Collections.copy(output,input); // error
11.
12.
13.
14. Enum - Example 11 How to define them .. public enum Flavor { CHOCOLATE(100), //declare all the possible values first. VANILLA(120), STRAWBERRY(80); private int fCalories; // can have state (member variables) int getCalories(){ // cusotm method return fCalories; } private Flavor(int aCalories){ // constructor fCalories = aCalories; } } How to use them … String getColor(Flavor flv){ // Used as normal java objects.. if(flv == Flavor.VANILLA) // “==“ can be used for value comparison return “White” ; ……. switch(flv) { case VANILLA : // You can use enums as case labels …… } String color = getColor(Flavor.VANILLA) // no constructor only constant values.
18. Enums are implicitly final subclasses of java.lang.Enum
19.
20. Methods come built in with enums to do do things like convert enums names to ordinals, and combos with enumset.
21. You can attach additional fields and code to enum constants.
22. enums are type safe. With Strings all your items in all categories are the same type. There is nothing to stop you from feeding a fruit category to an animal parameter.