Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.

Slides:



Advertisements
Similar presentations
Java Review Interface, Casting, Generics, Iterator.
Advertisements

1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Java Generics.
1 Generics, Type Safety, and Dynamic Data Structures.
Java 1.5 & Effective Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Building Java Programs
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
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.
Introduction to Java University of Sunderland CSE301 Harry R. Erwin, PhD.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Basic Java Syntax CSE301 University of Sunderland Harry R Erwin, PhD.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Recitation 4 Abstract classes, Interfaces. A Little More Geometry! Abstract Classes Shape x ____ y ____ Triangle area() base____ height ____ Circle area()
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1162 JDK 5.0 Features Christian Kemper Principal Architect Borland.
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Data Structures and Java CS 105. L7: Java Slide 2 Data structure Data structure defined: A systematic way of organizing and accessing data Examples Dictionary:
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Generic Programming  Object Type  Autoboxing  Bag of Objects  JCL Collections  Nodes of Objects  Iterators.
Introduction to Java COM379 (Part-Time) University of Sunderland Harry R Erwin, PhD.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Understanding Data Types and Collections Lesson 2.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Types in programming languages1 What are types, and why do we need them?
Introduction to Generics
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD.
ICOM 4035 – Data Structures Lecture 4 – Set ADT Manuel Rodriguez Martinez Electrical and Computer Engineering University of Puerto Rico, Mayagüez ©Manuel.
CMSC 330: Organization of Programming Languages Java Generics.
An Advanced Code Pattern: Inner Classes CSE301 University of Sunderland Harry R. Erwin, PhD Half Lecture.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Object Oriented Programming Lecture 2: BallWorld.
Building Java Programs Generics, hashing reading: 18.1.
Sixth Lecture ArrayList Abstract Class and Interface
Generics, Lambdas, Reflections
Java Programming Language
Java Basics Data Types in Java.
Presentation transcript:

Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD

Introduction Java 5 has been changed to improve the language. This lecture will discuss the changes. You will be tested on your knowledge of Java 5. References include: –McLaughlin and Flanagan, 2004, Java 1.5 Tiger: A Developer’s Notebook, O’Reilly –Flanagan, 2005, Java in a Nutshell, 5 th edition, O’Reilly

Topics Part 1 (today) Arrays Queues Overriding return types Unicode StringBuilder Generics Part 2 (next lecture) Enumerated types Boxing Annotations for/in Static imports Formatting Threading

Arrays Many static utility methods have been added for use with arrays. (Possible test questions follow!) To use them, import java.util.Arrays; Arrays.toString(theArray); lists the array contents Arrays.deepToString(theArray); Arrays.equals(array1,array2); tests two arrays for equality Arrays.hashCode(theArray); provides a hashcode (qv) for the array. Arrays.deepEquals(array1,array2); is similar. Arrays.deepHashCode(theArray); is similar.

Queues import Java.util.Queue; to use queues. That gives you a nice first-in-first-out data structure. Don’t use add() or remove() with it, as they throw exceptions. Instead, use offer() and poll(). offer() returns false if the queue is full, and poll() returns null if the queue is empty. If you want to see the next available entry in the queue without removing it, use element() or peek(). PriorityQueue is ordered using comparators. (It still isn’t as efficient as a C++ priority queue.) Possible test questions

Overriding return types In correct C++ implementations—I believe Visual C++ has finally fixed this—you can have a ‘covariant return’, where a method in a subclass returns a more specialised type instance than the overridden method in the base class. This is now available in Java 5. The return type of the subclass method must be an extension of the return type of the base class, and the compiler must be told you’re compiling Java 5 code. Possible test question.

Unicode 4.0 Java 5 supports Unicode 4.0, which defines some characters that require 21 bits in addition to the 16-bit standard Unicode 3.0 characters. You use int to represent these characters, and some of the static methods in the Character class now accept int arguments to deal with them. In a String, use a pair of char values to encode a 21-bit character.

StringBuilder This is a drop-in replacement for StringBuffer when thread safety is not an issue and speed is. (If thread safety matters, use StringBuffer.) StringBuffer and StringBuilder represent modifiable Strings, so you can edit them in many ways. The toString(); method for either converts its buffer into a String. To go the other direction, create a StringBuffer or StringBuilder object around the String.

Generics This is the most important new feature of Java 5. This allows a class to indicate that it uses or contains instances of some generic type. This increases the type safety of Java because the compiler can verify that you’re using that type correctly. A generic class or method looks like a C++ template class or method. Test questions are to be found throughout the material on generics!

Why Generics? This is pre-Java 5, legal, and unsafe List listOfStrings = getListOfStrings() for(Iterator i = listOfStrings.iterator(); i.hasNext();){ String item = (String)i.next(); Do something with the String item } You cannot remove the cast to String.

The Java 5 Solution This is legal only in Java 5 and much more safe: List listOfStrings = getListOfStrings(); for(Iterator i = listOfStrings.iterator(); i.hasNext();){ String item = i.next(); Do something with the String item } The cast to String is gone. Not much change? Wait.

Class Syntax for Generic class Foo { E can be used as a method argument type, a field member, or anywhere that a type can be used in a class definition. } (The naming convention for a parameter is to use a single uppercase letter.) E cannot be used in a static member field as the class that is shared among all instances of type Foo is Foo itself. Sorry! E can be used in static member methods.

Generics and Primitive Types They are incompatible, simply put. ‘E’ cannot be a primitive type. Use the corresponding wrapper types (Integer, Boolean, Float, Double, Character, etc.) and let autoboxing and unboxing (discussed later) handle the conversions. List will fail. List will work.

Generics and Collections All the collection classes support generics (in addition to their normal use in pre-Java 5 code). Map even takes two parameters. Map defines the keys to the map as type F, and the values as type B. Iterators are also parameterized (although they can also be nearly avoided using for/in loops, discussed later). Note you must parameterize the iterator if the collec- tion is parameterized. Finally, if you parameterize the iterator and not the collection, you’re playing with fire.

Parameterized Types as Method Arguments private void Foo(Bar argument); –This works fine. private Bar Foo(); –Returns an object of class Bar. private void Foo(Bar argument); –Can read but not write objects of type Quux internally, and you cannot construct an object of type Quux. private void Foo(Bar arg); –Is limited to N where N extends Baz. Similarly for class definitions and implements. Bar is not Bar.

Type Conversions with Parameterized Types Here be dragons! Parameterized types form a hierarchy, but the hierarchy is based on the base type, not on the types of the parameters. A LinkedList is a List, but not a LinkedList. (It is a LinkedList.) Why? Generics are a Java 5 add-on, and the class files must be Java 1-compatible and forgetting about the parameter types. (Inner classes are a similar add-on with some unexpected behaviour.) To avoid abuse, inheritance ignores parameters.

Arrays of Parameterized Types Here be more dragons! An array of type S[] is also of type T[] when T is a base class or interface of S. If you try to store an object of type T into an array of type S via an alias array of type T[], you get a class cast exception. If the type S were parameterized, this protection could not be enforced during run-time, as parameterized types are new in Java 5. So to prevent this, you are not allowed to create an array of a parameterized type! Sorry!