slide20-22 - Chapter 20 - 22 Advanced Java EE3206/EE5805...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 20 - 22 Advanced Java EE3206/EE5805 Java Programming & Application 1 What is a Data Structure? A data structure is a collection of data organized in some fashion. A data structure not only stores data, but also supports the operations for manipulating data in the structure. For example, an array is a data structure that holds a collection of data in sequential order. You can find the size of the array, store, retrieve, and modify data in the array. Array is simple and easy to use, but it has two limitations: Array Once an array is created, its size cannot be altered. Once Array provides inadequate support for inserting, deleting, sorting, and Array searching operations. EE3206/EE5805 Java Programming & Application 2 Object-Oriented Data Structure In object-oriented thinking, a data structure is an object that stores other objects, referred to as data or elements. So some people refer a data structure as a container object or a collection object. container collection To define a data structure is essentially to declare a class. The class for a data structure should use data fields to store data and provide methods to support operations such as insertion and deletion. To create a data structure is therefore to create an instance from the class. You can then apply the methods on the instance to manipulate the data structure such as inserting an element to the data structure or deleting an element from the data structure. EE3206/EE5805 Java Programming & Application 3 Four Classic Data Structures There are four classic dynamic data structures in Java There lists, stacks, queues, and binary trees. lists, A list is a collection of data stored sequentially. It supports insertion list and deletion anywhere in the list. A stack can be perceived as a special type of the list where insertions stack and deletions take place only at the one end, referred to as the top of a stack. A queue represents a waiting list, where insertions take place at the queue back (also referred to as the tail of) of a queue and deletions take place from the front (also referred to as the head of) of a queue. A binary tree is a data structure to support searching, sorting, inserting, binary and deleting data efficiently. EE3206/EE5805 Java Programming & Application 4 Java Collection Framework A collection is a container object that represents a collection group of objects, often referred to as elements. elements The Java Collections Framework supports three types of collections, named sets, lists, and maps. sets maps EE3206/EE5805 Java Programming & Application 5 The Set Interface The Set interface extends the Collection interface. It does not introduce new methods or constants, but it stipulates that an instance of Set contains no duplicate elements. The concrete classes that implement Set must ensure that no duplicate elements can be added to the set. That is no two elements e1 and e2 can be in the set such that e1.equals(e2) is true. EE3206/EE5805 Java Programming & Application 6 The List Interface A set stores non-duplicate elements. To allow duplicate elements to be stored in a collection, you need to use a list. A list can not only store duplicate elements, but can also allow the user to specify where the element is stored. The user can access the element by index. The Map Interface The The Map interface maps keys to the elements. The keys are like indexes. In List, the indexes are integer. In Map, the keys can be any objects. EE3206/EE5805 Java Programming & Application 7 Java Generics New feature in JDK (=JDK 1.5) to cope with the problems with New typecasting Downcasting is a potential hotspot for ClassCastException Downcasting ClassCastException Less readable Less Destroys benefits of a strongly typed language Destroys Example: ArrayList object Example: String myString = (String) myArrayList.get(0); //JDK1.4 Run-time checking Returning an instance of Object type EE3206/EE5805 Java Programming & Application 8 Why Generics? Solve the problem with typecasting Solve Benefits of using generics Benefits Allow a single class to work with a wide variety of types Allow Natural way of eliminating the need for casting Natural Preserves benefits of type checking Preserves Example: ArrayList object Example: //myArrayList<String> is a generic object String myString = myArrayList.get(0); // JDK5 Integer data = myArrayList.get(0); // ERROR! Compile-time checking Returning an instance of String type EE3206/EE5805 Java Programming & Application 9 Why Generics? Integer data = myArrayList.get(0); //ERROR Removal of downcasting doesn’t mean that you could Removal assign anything to the return value of the get method and do away with typecasting altogether Assign anything else besides a String to the output of the Assign String get method will cause a compile time type mismatch EE3206/EE5805 Java Programming & Application 10 Example of Using Generics Class //Code fragment ArrayList<String> genArrList = new ArrayList<String>(); new genArrList.add(“A generic string”); String myString = genArrList.get(0); JoptionPane.showMessageDialog(this, myString); EE3206/EE5805 Java Programming & Application 11 Declaring a Generic Class You may also declare your own generic class using the You following syntx: Class ClassName <Type1, Type2, …, TypeN> // Generic class with one type parameter Class BasicGeneric<A> { private A data; public BasicGeneric(A data) { this.data = data; } public A getData(){ return data; } } EE3206/EE5805 Java Programming & Application 12 Declaring a Generic class Public class GenSample { public String method 1 (String input) { String data1 = input; BasicGeneric<String> basicGeneric = new BasicGeneric<String>(data1); String data2 = basicGeneric.getData(); return data2; } Output: Some generic data 1234 public Integer method2(int input) { integer data1 = new Integer(input); BasicGeneric<integer> basicGeneric = new BasicGeneric <Integer>(data1); Integer data2 = basicGeneric.getData(); return data2; } public static void main(String args) { GenSample sample = new GenSample(); System.out.printIn(sample.method1(“Some generic data”)); System.out.printIn(sample.method2(1234)); } } EE3206/EE5805 Java Programming & Application 13 Declaring a Generic Class Declaration of the BasicGeneric class Declaration Class BasicGeneric<A> {…} Class Contains type parameter:<A> Contains Indicates that the class declared is generic class Indicates Class is not restricted to any specific reference type Class private A data; private The field data is of generic type, depending on the data type that the The BaiscGeneric object was designed to work with public A getData() ; public Returns a value of type A Returns The method will have a runtime data type The After you declare an object of type BasicGeneric, A is bound to a specific After data type (String and Integer in the example) EE3206/EE5805 Java Programming & Application 14 Declaration of field Declaration Declaration of the getData method Declaration Specifying Type Parameters Declaring an instance of the class Declaring Must specify the reference type to work with Must Examples: BasicGeneric<String> basicGeneric = new BasicGeneric<String>(data1); String data2 = basicGeneric.getData(); // the class works with variables of type String BasicGeneric<Integer> basicGeneric = new BasicGeneric<Integer>(data1); Integer data2 = basicGeneric.getData(); // the class works with variables of type Integer No need to typecast! No EE3206/EE5805 Java Programming & Application 15 Limitation on Generics Java generic types are restricted to reference types and Java won’t work with primitive datatypes BasicGeneric<int> basicGeneric = new BasicGeneric<int>(data1); //ERROR Solution Solution Wrap primintive types first Wrap Can use wrapper types as arguments to a generic type Can EE3206/EE5805 Java Programming & Application 16 Bounded Generics A type parameter can be unbounded. In this case any reference type type can be used as type argument to replace the unbounded type parameter in an instantiation of a generic type. Alternatively can have one or several bounds. In this case the Alternatively type argument that replaces the bounded type parameter in an instantiation of a generic type must be a subtype of all bounds. The syntax for specification of type parameter bounds is: The <TypeParameter extends Class & Interface1 & Interface2 & ... & Interface N > Interface1 Interface2 Interface EE3206/EE5805 Java Programming & Application 17 Bounded Generics Example: generic ScrollPane class Example: ScrollPane Template for an ordinary Container decorated Template Container decorated with scrolling functionality Runtime type of an instance of this class will be Runtime a subclass of Container Container It is said that Container is the static or general It Container is type EE3206/EE5805 Java Programming & Application 18 Bounded Generics // code fragments Class Container {…} Class Panel extends Container {…} Class Button {…} // MyPane can only be Container or its subtypes Class ScrollPane<MyPane extends Container> {…} Class TestScrollPane { Public static void main(String args) { ScrollPane<Panel> ScrollPane1 =new ScrollPane<Panel>(); ScrollPane<Button> scrollPane2 =new ScrollPane<Button>(); //ERROR! } } EE3206/EE5805 Java Programming & Application 19 Bounded Generics Advantages Advantages Achieves additional general type checking to Achieves guarantee that every instantiation of the generic type adheres to assigned bounds Can safely call any methods found in the general Can type If there is no explicit bound on the parameter, by If default the bound is Object EE3206/EE5805 Java Programming & Application 20 Generic Method Not only types can be generic, but methods can be Not generic, too. Static and non-static methods as well as constructors Static can have type parameters. The syntax for declaration of the formal type The parameters is similar to the syntax for generic types. The type parameter section is delimited by angle The brackets and appears before the method's return type. Its syntax and meaning is identical to the type parameter list of a generic type. EE3206/EE5805 Java Programming & Application 21 Declaring a Generic Method Java also uses a type-inference mechanism Java Automatically infers the types of polymorphic methods based on Automatically the types of arguments Reduces wordiness and complexity of a method invocation Reduces // class Utility can be generic or non-generic Class Utilities { /* T implicitly extends Object */ public static <T> ArrayList<T> make(T first) { return new ArrayList<T>(first); } } … // To construct a new instance of ArrayList<Integer> Utilities.make(Integer(0)); Implicitly tells T is Integer EE3206/EE5805 Java Programming & Application 22 ...
View Full Document

This note was uploaded on 01/11/2011 for the course EE 3206 taught by Professor Cwting during the Spring '07 term at City University of Hong Kong.

Ask a homework question - tutors are online