• 670 likes • 685 Views
Learn about the basics of generics in Java, including type safety, implementing generics, type erasure, bounded type parameters, and casting to generic types.
E N D
Lec 09 Agenda Generics Searching and sorting, logs, Collections (2:12) https://www.youtube.com/watch?v=1BIke9mprDw Data structures JavaFX - - install Scene Builder Game features.
Type Safety The initial Java collections stored values of type Object. They could store any type, since all types are subclasses of Object. But you had to cast the results, which was tedious and error-prone. Examining the elements of a collection was not type-safe. // in Java 1.4: ArrayList names = new ArrayList(); names.add("Marty Stepp"); names.add("Stuart Reges"); String teacher = (String) names.get(0); // this will compile but crash at runtime; bad Point oops = (Point) names.get(1);
Generics List<Type> name = new ArrayList<>(); Since Java 1.5, when constructing a java.util.ArrayList, we specify the type of elements it will contain between < and >. We say that the ArrayList class accepts a type parameter,or that it is a genericclass. Use of the "raw type" ArrayList without <> leads to warnings. List<String> names = new ArrayList<>(); names.add("Marty Stepp"); names.add("Stuart Reges"); //names.add(new Rectangle(1,2,3,4); //CT error String teacher = names.get(0); // no cast Point oops = (Point) names.get(1);// RT error TypeSafetyDriver.java
Implementing generics // a parameterized (generic) class public class Name<Type> { or public class Name<Type, Type, ..., Type> { By putting the Type in <>, you are demanding that any client that constructs your object must supply a type parameter. You can require multiple type parameters separated by commas. The rest of your class's code can refer to that type by name. The convention is to use a 1-letter name such as:T for Type, E for Element, N for Number, K for Key, or V for Value. The type parameter is instantiated by the client. (e.g. E → String) BasicDriver.java
Generics and arrays (15.4) public class Foo<T> { private T myField; // ok private T[] myArray; // ok public Foo(T param) { myField = new T();// error myArray = new T[10]; // error } } You cannot instantiate objects or arrays of a parameterized type.
Generics/arrays, fixed public class Foo<T> { private T myField; // ok private T[] myArray; // ok @SuppressWarnings("unchecked") public Foo(T param) { myField = param; // ok T[] a2 = (T[]) (new Object[10]); // ok } } But you can create variables of that type, accept them as parameters, return them, or create arrays by casting Object[]. Casting to generic types is not type-safe, so it generates a warning.
Type erasure All generics reference types become type Object once compiled. One reason: Backward compatibility with old byte code. List<String> lst1 = new ArrayList<String>(); List<Integer> lst2 = new ArrayList<Integer>(); lst1.getClass() == lst2.getClass() // true You cannot use instanceof to discover a type parameter. Collection<?> cs = new ArrayList<String>(); if (cs instanceof Collection<String>) { // illegal } GetClassType.java
Comparing generic objects public class ArrayList<E> { ... public int indexOf(E value) { for (int i = 0; i < size; i++) { // if (elementData[i] == value) { if (elementData[i].equals(value)) { return i; } } return -1; } } When testing objects of type E for equality, must use equals
A generic interface // Represents a list of values. public interface List<E> { public void add(E value); public void add(int index, E value); public E get(int index); public int indexOf(E value); public boolean isEmpty(); public void remove(int index); public void set(int index, E value); public int size(); } public class ArrayList<E> implements List<E> { ... public class LinkedList<E> implements List<E> { ... java.util.List.java
Generic methods public static <Type>returnTypename(params) { When you want to make just a single (often static) method generic in a class, precede its return type by type parameter(s). public class Collections { ... public static <T> void copy(List<T> dst, List<T> src) { for (T t : src) { dst.add(t); } } } PrintArrayDriver.java
Bounded type parameters <Type extends SuperType> An upper bound; accepts the given supertype or any of its subtypes. Works for multiple superclass/interfaces with & : <Type extends ClassA & InterfaceB & InterfaceC & ...> <Type super SuperType> A lower bound; accepts the given supertype or any of its supertypes. Example: // tree set works for any comparable type public class TreeSet<T extends Comparable<T>> { ... } ConsumerDriver.java & ProducerDriver.java
Generics and casting Casting to generic type results in a warning. List<?> l = new ArrayList<String>(); // ok List<String> ls = (List<String>) l; // warn The compiler gives an unchecked warning, since this isn't something the runtime system is going to check for you. Usually, if you think you need to do this, you're doing it wrong. The same is true of type variables: public static <T> T badCast(T t, Object o) { return (T) o; // unchecked warning }
Arrays versus Collections Array • Holds objects of known type. • Fixed size. Collections • Generalization of the array concept. • Set of interfaces defined in Java for storing Objects. • Multiple types of objects. • Resizable.
Using Interfaces with Collections • Interfaces are used for flexibility reasons • Programs that use an interface are not coupled to a specific implementation of a collection. • It is easy to change or replace the underlying collection class with another class that implements the same interface. • Map map = new HashMap(); • Map map = new TreeMap();
What is Log Logs describes how a system decays. Exponents grow: 25 = 32 Logs decay : Log2 32 = 5
Some Log applications You’re in a Tennis match with 15 other competitors. Single elimination. How many games will you need to win to be champion? You discover a paleolithic spear. The wood of the spear emits 1/128 or 0.078125 of the original radioactive strength of C14 which is formed at photosynthesis and has a half-life of 5700 years. Date the spear.
BindarySearchFrame.java Some Log applications You have a sorted set of 5 billion records. 5234567000. What is the maximum number of times I need to iterate to find a record? Log2 5234567000 = 32.28 ~ 33 times. (2:12) https://www.youtube.com/watch?v=1BIke9mprDw
(2:12) https://www.youtube.com/watch?v=1BIke9mprDw Searching Linear search O(n) --slow Binary search O(log2n) --fast Refresher on logs: If 23 = 8 then log28 = 3 Hashed search O(1) –fastest
Sorting SelectionSort O(n2) –-slow MergeSort O(n * log2n) –- fast HeapSort O(n * log2n) –- fast QuickSort O(n * log2n) –- fast
ArrayList.java & SimpleLinkedList.java The Node class Node<T> { private T typValue; private Node<T> nodNext; … } //we can create 95% of all data structures from this self-referential Node.
Roll Your Own • LinkedList • Stack • Queue • HashTable • Tree • others...
Applications of logs If you're playing in single-elimination (sudden-death) tournament with 16 players in your draw, how many matches would you need to win in order to win the tournament? Log216 You're searching a sorted set of 64 elements, what is the maximum number of times you would need to search this set? Log264
Applications of logs The radioactive half-life of Carbon-14 is 5730 years. You find a fossil whose Carbon-14 signature has a radioactive strength of 1/128 of the original strength. How old is this fossil?
Download - Scene Builder for Rapid UI Design • WYSIWYG GUI design tool for the JavaFX platform • Enables designing user interface screens by simply dragging and positioning GUI components from a palette onto a scene • Generates files in FXML format that can be used within a project in any IDE such as NetBeans or Eclipse • Can be used to create GUI for desktop and Web applications • Currently in Early Access (by invitation)
JavaFX http://download.oracle.com/otndocs/products/javafx/2/samples/Ensemble/index.html Ensemble.jar
Threads in JavaFX The system runs two or more of the following threads at any given time. 1. JavaFX application thread: This is the primary thread used by JavaFX application developers. Any “live†scene, which is a scene that is part of a window, must be accessed from this thread. A scene graph can be created and manipulated in a background thread, but when its root node is attached to any live object in the scene, that scene graph must be accessed from the JavaFX application thread. This enables developers to create complex scene graphs on a background thread while keeping animations on 'live' scenes smooth and fast. The JavaFX application thread is a different thread from the Swing and AWT Event Dispatch Thread (EDT), so care must be taken when embedding JavaFX code into Swing applications. 2. Prism render thread: This thread handles the rendering separately from the event dispatcher. It allows frame N to be rendered while frame N +1 is being processed. This ability to perform concurrent processing is a big advantage, especially on modern systems that have multiple processors. The Prism render thread may also have multiple rasterization threads that help off-load work that needs to be done in rendering. 3. Media thread: This thread runs in the background and synchronizes the latest frames through the scene graph by using the JavaFX application thread. Threads in Java Swing 1. Event Dispatch Thread
JavaFX Runtime High Level Architecture JavaFX Glossary • Glass Windowing Toolkit: Provides native operating services, such as managing the windows, timers, and surfaces • Prism: Graphics pipeline that can run on hardware and software renderers • Quantum Toolkit: Ties Prism and Glass together and makes them available to the JavaFX APIs • This is completey seemless in Java8
Let’s Compare: JavaFX 2.0 public class JavaFXTest extends Application { @Override public void start(Stage stage) { Group root = new Group(); Scenescene = new Scene(root,100,100); stage.setScene(scene); Circle c1 = new Circle(50.0f, 50.0f, 50.0f, Color.RED); root.getChildren().add(c1); stage.setVisible(true); } public static void main(String a[]) { Launcher.launch(JavaFXTest.class, null); } }
Let’s Compare: FXML <BorderPane> <center> <Circle radius=“50” centerX=“50” centerY=“50”/> </center> </BorderPane> public class JavaFXTest extends Application { @Override public void start(Stage stage) { stage.setTitle(“FXML Example”); Parent root = FXMLLoader.load(getClass().getResource(“example.fxml"), ResourceBundle.getBundle(“r.fxml_example")); stage.setScene(new Scene(root)); stage.show(); } }
Scene Graph • Directed Acyclic Graph • Parents and children • Representation of the GUI components
Media • JavaFX supports both visual and audio media • Cross-platform JavaFX media file format (fxm, mp3) • Platform specific formats supported via native players • Media class represents a media file • MediaPlayer provides control of the media rendering • MediaView uses MediaPlayer to render media as Node • Many MediaViews can use the same MediaPlayer (cheaply)