CS2013 Lecture 3 John Hurley Cal State LA.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Java Generics.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L13 (Chapter 21) Generics.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
Java Generics.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Effective Java: Generics Last Updated: Spring 2009.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Introduction to Generics
CS-2851 Dr. Mark L. Hornick 1 Generic Java Classes Implementing your own generic classes.
Generic Instructor : Sarah Alodan. Problem?! Java code used to look like this: public class Courses { public static void main(String[] args) { ArrayList.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
April 13, 1998CS102-02Lecture 3-1 Data Types in Java CS Lecture 3-1 Java’s Central Casting.
CMSC 202 ArrayList Aug 9, 2007.
Chapter VII: Arrays.
Java Generics.
Sixth Lecture ArrayList Abstract Class and Interface
Lecture 3 Linear Search and Binary Search ArrayLists
John Hurley Cal State LA
Inheritance and Polymorphism
ADT’s, Collections/Generics and Iterators
CIS265/506 Cleveland State University – Prof. Victor Matos
More on Java Generics Multiple Generic Types Bounded Generic Types
John Hurley Cal State LA
Chapter 20 Generic Classes and Methods
COP 3503 FALL 2012 Shayan Javed Lecture 8
Lecture 10: More on Methods and Scope
Generics, Lambdas, Reflections
CompSci 230 Software Construction
Type Systems Terms to learn about types: Related concepts: Type
Continuing Chapter 11 Inheritance and Polymorphism
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Chapter 9 Inheritance and Polymorphism
Chapter 19 Generics Dr. Clincy - Lecture.
Generics (Parametric Polymorphism)
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Generics 27-Nov-18.
CMSC 202 ArrayList Aug 9, 2007.
Generics.
Generic programming in Java
CS2013 Lecture 4 John Hurley Cal State LA.
Chapter 19 Generics.
Chapter 21 Generics.
CMSC 202 ArrayList Aug 9, 2007.
slides created by Ethan Apter
CMSC 202 Generics.
Generics, Lambdas, Reflections
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Interfaces.
Chapter 11 Inheritance and Polymorphism Part 2
Review: libraries and packages
Generics 2-May-19.
CS2013 Lecture 3 John Hurley Cal State LA.
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
The beginning of media computation Followed by a demo
SPL – PS1 Introduction to C++.
CS 2013 Lecture 6: Generics.
Presentation transcript:

CS2013 Lecture 3 John Hurley Cal State LA

Data Structures Memorize this definition! A data structure is a systematic way to organize data in order to improve the efficiency of algorithms that will use the data.

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.

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>

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);

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. <script lang = "JavaScript"> function printOut(v){ document.write(v + "<br />"); } var myName = "Earl"; var myAge = 42; printOut(myName); printOut(myAge); </script>

Generics We can get more flexibility 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.

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.

Generics The generic type is defined with a placeholder that is essentially a variable representing the parameterizing type, for example ArrayList<E>

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

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

Generic Instantiation 12 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

13 Generic ArrayList

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

Generic Methods public static <E> void print(E[] list) { 15 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.

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.

17 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.

Bounded Generic Type package demos; import java.util.ArrayList; 18 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;

19 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; }

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

Type Erasure and Restrictions on Generics 21 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.

22 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.

23 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

24 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()); }

25 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

26 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);

27 Data Files With .jars Choose Build Path/Configure Build path, then source. You will see this dialog box

28 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.