Download presentation
Presentation is loading. Please wait.
1
CS 2013 Lecture 6: Generics
2
Generics Recall that a list is a list of objects of some type. We show that using syntax like this: List<Student> students; List is a generic data structure, meaning that we can have lists of many different types of objects. It is parameterized by the data type that the list will hold. Interfaces may be parameterized in the same way. For example, when we declared that Student implemented Comparable, the interface was parameterized by the same class Student. This means that the compareTo() method compares the current Student to another Student.
3
Generics Many other data structures we will study in this course are also suitable for handling objects of many different types. The same notation is used: Stack <Rectangle>
4
Generics Java is a strongly-typed language, one in which references can only be passed if they are of the same type the receiver expects. It is also statically-typed; type checking is done at compile time, not at run time. Using a type incorrectly, for example by sending a parameter of an incorrect type, is a syntax error. Compare this Java code to the JavaScript on the next slide: public static void main(String[] args) { String myName = "Earl"; printOut(myName); } public static void printOut(String s) { System.out.println(s);
5
Generics JavaScript is dynamically-typed; type checking is done at runtime, not compile time. Sending an incorrect type as a parameter is a runtime error, but if all operations in a function are meaningful for the data types passed, the function will execute. <html> <script lang = "JavaScript"> function add(num1, num2){ return num1 + num2; } var myName = "Earl"; var answer = 42; var unlucky = 13; document.write(answer + "+" + unlucky + "=" + add(answer, unlucky) + "<br />"); document.write(myName + "+" + myName + "=" + add(myName, myName) + "<br />"); </script> </html>
6
Generics We can get more flexibility in Java by being as general as possible with the type of the method parameters public static void main(String[] args) { String myName = "Earl"; printOut(myName); int age = 42; printOut(age); } public static void printOut(Object o) { System.out.println(o); (The compiler and JVM "box" the int automatically into an Integer, which is an object.) The potential problem with this is that it may be *too* general. If we want to write a method with operations that will work with either Students or FacultyMembers, but not with Monsters, we need to be more specific in the method signature.
7
Generics Generic classes and data structures are designed with the capability to incorporate any of a range of other types. They are parameterized by the type that is "plugged in". This is somewhat similar to the concept of an array as a collection of values of the same data type. Unlike arrays, though, generic data types can only use reference types as their underlying type You can create an ArrayList<Integer>, using the class Integer, but not an ArrayList <int> using the primitive data type int. It is possible to create Lists in Java which are not parameterized and can accept values of any type. This is left over from before generics were introduced to Java. Don’t do this.
8
Generics The generic type is defined with a placeholder that is essentially a variable representing the parameterizing type, for example ArrayList<E>
9
Generics We can and should declare variables with the least-specific type that will work. For example, we can declare a variable of type List<E> and then instantiate an ArrayList<E> and assign this object to the variable. This way, if we decide later to use some other kind of List, it is very easy to change the code. We can even write code in which the type of list depends on things that happen at runtime. This only works if we can limit our use of methods to those that are in the List interface Similarly, we can choose the most general "plugged in" type available and actually add objects of subclasses or implementing classes to the generic data structure
10
Generics The rules for which types can be used in a parameterized data structure are similar to the rules for variable types: If the data structure calls for a type, you can add objects of that type or its subtypes, but not of its supertypes A subtype may be either a subclass, a subinterface, or a class that implements an interface This is easy to understand using some examples: Suppose Monster is a class with two subclasses, Zombie and Demon, which do not have any subclasses of their own An ArrayList<Monster> can hold any combination of Monsters, Zombies, and Demons An ArrayList<Zombie> can only hold Zombies Suppose TVShow is an interface, and the classes GameShow and SitCom implement it and do not have any subclasses An ArrayList<TVShow> can hold any combination of GameShows and SitComs. An ArrayList<GameShow> can only hold GameShows
11
Generic Instantiation
11 Generic Type Although you could achieve similar results by just using the type Object instead of using generics, generics provide stricter compile-time type checking. This replaces runtime errors with syntax errors, which are much easier to deal with. Generic Instantiation Runtime error Improves reliability Compile error
12
Generic Interfaces public interface MyMath<T> {
Several sections of CS2012 over the past year have completed a lab using the MyMath interface: public interface MyMath<T> { public T add(T o); public T subtract(T o); public T divide(T o); public T multiply(T o); } In implementing MyMath <T>, you chose the type that T represents and applied binary operations like add(), whose operands were the current object and an object of class T
13
public static <E> void print(E[] list) {
13 Generic Methods Methods in non-generic classes may take generic parameters, but the syntax for this may be unexpected: public static <E> void print(E[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); } Try this with an array of Doubles, Strings, etc. It won’t work with a primitive data type.
14
public static <E> void print(E[] list) {}
Generics Note that, when we implement MyMath <T>, we define what type T stands for. Therefore, the parameter types for the methods are determined at compile time, and there is no ambiguity for the compiler. A generic method like public static <E> void print(E[] list) {} is different, because the type of the generic parameter may not be known until runtime.
15
15 Bounded Generic Type Methods that use generic types can limit the possible types to ones that extend a particular class or implement a particular interface For example, if your method finds the largest element in a list by using compareTo(), it will only work if the parameter objects include this method. You can make sure they do by only using objects of classes that implement Comparable.
16
Bounded Generic Type 16 package demos; import java.util.ArrayList;
import java.util.List; public class Demo { public static void main(String[] args) { List<String> myList = new ArrayList<String>(); String[] myArray = {"Godzilla", "Dracula", "Frankenstein"}; for(String s:myArray) myList.add(s); System.out.println(min(myList)); } public static <E extends Comparable <E>> E min(List<E> theList) { E smallest = theList.get(0); for (E e: theList) if(e.compareTo(smallest) < 0) smallest = e; return smallest;
17
17 Bounded Generic Type The placeholder E is an arbitrary choice. This min method is equivalent to the one on the last slide: public static <Z extends Comparable <Z>> Z min(List<Z> theList) { Z smallest = theList.get(0); for (Z z: theList) if(z.compareTo(smallest) < 0) smallest = z; return smallest; }
18
Generics The Java collections we have been using are themselves programmed in Java and follow some of the same patterns we are learning. List<E> is an interface There is a List class, but it is the old, pre-generics List. Eclipse or the compiler will produce a warning but let you use it. Don’t. ArrayList<E> is a concrete class that extends Abstract List<E>, which implements List <E> There are various other interfaces and classes involved too
19
19 Type Erasure and Restrictions on Generics Generics are implemented using type erasure. The compiler uses the generic type information to compile the code, and in particular to do type checking. The generic type is ignored afterwards. The bounds on the parameterizing type are available to the compiler, but not at run time. This approach enables the generic code to be backward-compatible with legacy code (code in old forms of Java) that uses raw types.
20
20 Compile Time Checking For example, the compiler checks whether the parameterizing type is correct for the following code in (a) and translates it into the equivalent code in (b) for runtime use. The code in (b) uses the Object type.
21
21 Type Erasure A generic class is shared at runtime by all its instances regardless of its actual generic type. GenericStack<String> stack1 = new GenericStack<String>(); GenericStack<Integer> stack2 = new GenericStack<Integer>(); Although GenericStack<String> and GenericStack<Integer> are two types, there is only one class GenericStack loaded into the JVM. Stack1 and stack2 in this example are still two different instances of the GenericStack class
22
22 Type Erasure Type erasure is the reason why you can't construct objects of a generic class. The JVM won’t know at runtime what the class should be: This will *NOT* work: public static <E> void addOne(List<E> theList) { theList.add(new E()); }
23
23 Example of Generics: Generic Binary IO package lab2;
import java.io.Serializable; public class Student implements Serializable { private static final long serialVersionUID = L; private String name; private double gpa; public Student(String name, double gpa){ this.name = name; this.gpa = gpa; } public String getName() { return name; public void setName(String name) { public double getGpa() { return gpa; public void setGpa(double gpa) { @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; Student otherStudent = (Student) obj; if (name.equals(otherStudent.name) && gpa == otherStudent.gpa) public String toString(){ return name + "; gpa:" + gpa;
24
24 Example of Generics: Generic Binary IO package lab2;
import java.io.Serializable; package lab2; import java.util.ArrayList; import java.util.List; public class Course implements Serializable { private static final long serialVersionUID = L; private String courseName; private List<Student> students; public Course() { students = new ArrayList<Student>(); } public String getCourseName() { return courseName; public void setCourseName(String courseName) { this.courseName = courseName; public List<Student> getStudents() { return students; public void addStudent(Student s) { students.add(s); @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; Course otherCourse = (Course) obj; if (courseName.equals(otherCourse.courseName) && students.equals(otherCourse.students))
25
public interface Persister <T> {
25 Example of Generics: Generic Binary IO package lab2; import java.io.File; import java.util.List; public interface Persister <T> { public void saveObjectToFile(File f, T ob); public void saveListToFile(File f, List<T> myList); public T readObjectFromFile(File f); public List<T> readListFromFile(File f); }
26
26 Example of Generics: Generic Binary IO package lab2;
import java.io.File; import java.io.BufferedOutputStream; import java.io.BufferedInputStream; import java.io.ObjectInputStream; import java.io.FileOutputStream; import java.io.FileInputStream; import java.util.List; import java.io.ObjectOutputStream; public class PersisterImpl<T> implements Persister<T> { ObjectOutputStream out = null; public void saveObjectToFile(File f, T ob){ new FileOutputStream(f))); out = new ObjectOutputStream(new BufferedOutputStream( try { } catch (Exception e) { out.close(); out.writeObject(ob); } e.printStackTrace(); public void saveListToFile(File f, List<T> myList){ out.writeObject(myList);
27
27 Example of Generics: Generic Binary IO
public T readObjectFromFile(File f) { ObjectInputStream in = null; T retrievedObject = null; try { in = new ObjectInputStream(new BufferedInputStream( new FileInputStream(f))); retrievedObject = (T) in.readObject(); in.close(); } catch (Exception e) { e.printStackTrace(); } return retrievedObject; public List<T> readListFromFile(File f) { List<T> retrievedList = null; retrievedList = (List<T>) in.readObject(); return retrievedList;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.