Download presentation
Presentation is loading. Please wait.
1
John Hurley Cal State LA
CS203 Lecture 5 John Hurley Cal State LA
2
Data Structures Memorize This!
A data structure is a systematic way to organize information in order to improve the efficiency of algorithms that will use the data
3
Generics Some data structures are suitable for handling objects of many different types. Every ArrayList is a list of objects of some type, but the types might be Strings, Rectangles, or any other objects.
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. 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 <script lang = "JavaScript"> function printOut(v){ document.write(v + "<br />"); } var myName = "Earl"; var myAge = 42; printOut(myName); printOut(myAge); </script>
6
Generics We can do something like this by being as vague 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 classes or interfaces 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 unless you find some very good reason.
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
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 ArrayList
13
Generic Interfaces public interface MyMath<T> {
Several sections of CS202 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
14
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. The generic method public static <E> void print(E[] list) is different, because the type of the generic parameter may not be known until runtime.
15
Generic Methods public static <E> void print(E[] list) {
Methods in non-generic classes may take generic parameters, but the syntax for this may be unexpected: Generic 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.
16
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.
17
Bounded Generic Type 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;
18
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; }
19
Bounded Generic Type public static void main(String[] args ) {
Rectangle rectangle = new Rectangle(2, 2); Circle9 circle = new Circle9(2); System.out.println("Same area? " + equalArea(rectangle, circle)); } public static <E extends GeometricObject> boolean equalArea(E object1, E object2) { return object1.getArea() == object2.getArea();
20
Wildcards ? unbounded wildcard ? extends T bounded wildcard
? super T lower bound wildcard
21
Generic Types and Wildcard Types
22
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 class that extends Abstract List<E>, which implements List There are various other interfaces and classes involved too
23
Type Erasure and Restrictions on Generics
Generics are implemented using type erasure. The compiler uses the generic type information to compile the code, but erases it 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.
24
Compile Time Checking For example, the compiler checks whether generics is used correctly for the following code in (a) and translates it into the equivalent code in (b) for runtime use. The code in (b) uses the raw type.
25
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
26
Type Erasure Type erasure is the reason why you can't construct objects of a generic class, even though it seems that the JVM should know at runtime what the class should be: This will *NOT* work: public static <E> void addOne(List<E> theList) { theList.add(new E()); }
27
Data Files With .jars Generally, you should ask users for data file paths, not hard code them. If the user needs to be able to use multiple files in similar ways (eg the application can keep separate sets of similar data), s/he needs to be able to choose paths and file names However, if a data file is unlikely to change or holds configuration data internal to the application, it may be appropriate to hard code a file name. This is easy if you are running applications in eclipse or from the .class files at a command line. The next few slides show how to do this with a .jar file
28
Data Files With .jars Choose Build Path/Configure Build path, then source. You will see this dialog box
29
Data Files With .jars Add the root of the project. This is the base of the classpath for the project. Exclude src but leave the separate reference to it.
30
Data Files With .jars Put the data file in a separate folder in the project, outside src. Create an InputStream this way. The first slash in the path makes the relative path start at the root of the classpath for the application, inside the .jar: InputStream input = getClass().getResourceAsStream("/data/" + wordFile); Use a Scanner that scans from your InputStream: freader = new Scanner(input);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.