210 likes | 335 Views
This comprehensive guide covers Java Generics, discussing their purpose, advantages, and practical implementations. Generics allow classes and interfaces to operate on specified types, improving type safety and reducing runtime errors such as ClassCastException. Learn how to define and utilize parameterized types, create your own generic classes, and understand key concepts like type erasure and wildcard types. Discover the importance of generics in making your code more flexible, maintainable, and secure while preventing misuse of raw types.
E N D
Generics Parametrized classes and methods Generics
What are generics • Generics are classes or interfaces that can be instantiated with a variety of types. • They have 1 or more formal type parameters • Using a generic you specify an actual type • Also known as “parametrized types” • Or types with “holes” Generics
Before generics List myList = new ArrayList(); myList.add(“Anders”); … String str = (String)myList.get(0); Type casts are generally considered bad since they may fail at runtime If you add something that is not a string myList.add(new Integer(56)); After generics List<String> = new ArrayList<String> (); myList.add(“Anders”); … String str = myList.get(0); myList is now typed String in this case We don’t need type casting. We cannot add anything but Strings myList.add(56); Does not compile No more type casts Generics
Benefits of generics • Making code better • Runtime: No ClassCastException • Compile time: Compiler discovers wrong uses of types. • Making code more flexible • Generic classes can be instantiated with different types. Generics
Type inference- the ”diamond” • Java 7 feature • Java 6 • List<String> someList = new List<String>(); • Java 7 • List<String> someList = new ArrayList<>(); • Map<T, Set<E>> multiMap = new HashMap<>(); • The compiler will automatically “calculate” there type of the right hand side object • <> is supposed to look like a diamond!? Generics
Defining and using your own generic class • Definition public class Catalog<T> { List<T> catalog = new ArrayList<T>(); public boolean add(T element) { catalog.add(element); } } • Usage Catalog<Borrower> bc = new Catalog<Borrower>(); Catalog<Book> bookCatalog = new Catalog<Book>(); Generics
Erasure • At compile-time all the types are checked and removed (erased) from the class file. • What is left is called the “raw type”. • The class file has no knowledge of the types. • Example • Catalog<Borrower> is “erased” to Catalog Generics
Erasure (2) • Types are checked and removed (erased) • No generics in the JVM. • All instances of a generics class have the same run-time class List<String> list = new ArrayList<String>(); System.out.println("list type: " + list.getClass()); • Writes ArrayList, nothing said about String. if (list instanceof ArrayList<String>) … • Illegal, since <String> is not present at run-time if (list instanceof ArrayList) … • Legal Generics
Relationships among generics • Object is a super type of String. • ArrayList<Object> is not a super type of ArrayList<String> • Object and String are erased at compile time. • Runtime system has no knowledge of the types. Generics
Raw types • The raw types are the generic types, but without a specified actual type • ArrayList, Collection, Catalog • Collection is “equal” to Collection<?> • but not Collection<Object> Generics
An example: Using raw types to break “security” public String loophole(Integer x) { List<String> ys = new LinkedList<String>(); List xs = ys; xs.add(x); return ys.get(0); } • We used xs as an old-fashioned (un-typed) alias to ys. Using xs we were able to insert an Integer into ys. • Generally • Avoid un-typed collections. From: Gilad Bracha: Generics in the Java Programming Language, page 12 Generics
Wildcard types • Yet another feature to solve the problems with relationships among generics. • New syntax: ? • MyClass<?> • MyClass of any type • Example • Boolean java.util.Collection.containsAll(Collection<?> c) • http://java.sun.com/javase/6/docs/api/java/util/Collections.html Generics
Wild card types with upper bounds • Sometimes the types cannot be chosen completely free • We have to make sure that the type has certain features • Example • Java.util.Collection.addAll(Collection<? extends E> c) • http://java.sun.com/javase/6/docs/api/java/util/Collections.html • Can use any collection of types that extends E (which is the element type of this Collection • The type is said to have an “upper bound” (in the class hierarchy) • In this case E Generics
Generics methods • Methods (static and non-static) can be generic • Syntax • <T> T method(T element) { …} • Most often with static methods • Example • <T> List<T> Collections.synchronizedList(List<T> list) • http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html Generics
Wild cards with lower bounds • Most often used with generic methods • Examples from java.util.Collections • static <T> void fill(List<? super T> list, T obj) • Replaces all of the elements of the specified list with the specified element. • T is the type of the new object • List must have elements which are super types of T • T is a lower bound in the object hierarchy • Example • List<JComponent> list; • … • Collections.fill(list, new JButton()); Generics
Bounded wildcards • ? extends T upper bound • Unknown type that is a subtype of T • Or T itself • ? super T lower bound • Unknown type that is a super type of T • Or T itself Generics
Comparing and sorting • The class java.util.Collections has static methods for sorting elements in lists • <T extends Comparable<? super T>> void sort(List<T> list) • <T> void sort(List<T> list, Comparator<? super T> c) • This is a lot of syntax! • First sort method orders elements according to the natural order • int: 1,2,3,4, etc. • String: a, b, c, etc. • Second sort method orders elements according to the specified comparator • A comparator compares 2 elements and returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. Generics
Using generics with legacy code • Legacy code means old code • In this case code written prior to Java 5.0 is considered old • How do you deal with legacy classes that don’t use generics (but ought to)? • Examples • Generics – legacycode.Cat.java • Compiler sends you warnings • … uses unchecked or unsafe operations • When you call methods on a raw type • … unchecked cast • When you cast from raw to generic type. • You may have to live with such warnings • Or change the legacy code Generics
Other programming languages • C++ templates • Code is expanded • No erasures (no wildcards): Code bloat Generics
References • Sun MicrosystemsThe Java Tutorial • Generics http://java.sun.com/docs/books/tutorial/java/javaOO/generics.html • Easy introduction to generics. • Gilad Bracha • http://java.sun.com/docs/books/tutorial/extra/generics/index.html • Gilad BrachaGenerics in the Java Programming Language, Sun Microsystems 2004 • http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf • Also known as the ”Generics Tutorial” • Thorough introduction to generics. Generics
More references • Niemeyer & KnudsenLearning Java, 3rd edition, O’Reilly 2005 • 8. Generics, page 214-248 Generics