CompSci 100E 40.1 Java 5 New Features  Generics  Enhanced for loop  Autoboxing/unboxing  Typesafe enums  Other  Varargs  Static Import  Metadata.

Slides:



Advertisements
Similar presentations
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Advertisements

Review Generics and the ArrayList Class
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
1-May-15 Java 1.5. Reason for changes “The new language features all have one thing in common: they take some common idiom and provide linguistic support.
Java 5.0 Java 5 – Tiger Short history. Where AP is headed: likely features that will end up in the subset. Other fun features to use if you choose.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Java 1.5 & Effective Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
J2SE 5.0 New Features. J2SE 5.0 aka JDK 1.5 aka Tiger.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
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.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
(c) University of Washington14-1 CSC 143 Java Collections.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
Effective Java: Generics Last Updated: Spring 2009.
1162 JDK 5.0 Features Christian Kemper Principal Architect Borland.
ArrayList, Multidimensional Arrays
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types.
© 2007 Lawrenceville Press Slide 1 Chapter 10 Arrays  Can store many of the same kind of data together  Allows a collection of related values to be stored.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
24-Oct-15 Java Java beta 1 (“Tiger”) Released February 4, Themes Ease of Development Scalability.
Chapter 18 Java Collections Framework
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
CompSci Arrays  Aggregate data type  Deal with items of same type  Lists of words  Numbers  Analogies  Mailboxes in post office  CD racks.
Programming With Java ICS201 1 Chapter 14 Generics and The ArrayList Class.
Java Generics Compiled from Core Java Technologies Tech Tips By Billy B. L. Lim.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Java 1.5 The New Java Mike Orsega Central Carolina CC.
Objects First With Java A Practical Introduction Using BlueJ Supplementary Material for Java
Introduction to Generics
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Java 5 Part 2 CSE301 University of Sunderland Harry Erwin, PhD.
Georgia Institute of Technology What is new in Java 5.0 (1.5)? Barb Ericson Georgia Institute of Technology June 2006.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 8 Lists, Iterators, and Doubly Linked Lists.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
Object Oriented Programming in Java Lecture 14. Review Quiz 1. Write a method which gets an Object and call all its available ‘get’ Methods and print.
Enterprise Java Java SE 5 TM Language Feature Enhancement Primary Source: New Features and Enhancements J2SE 5.0
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
Bart van Kuik Application Developer Oracle Corporation.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
New Java Features Advanced Programming Techniques.
EKT472: Object Oriented Programming
CMSC 202 ArrayList Aug 9, 2007.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Sixth Lecture ArrayList Abstract Class and Interface
Introduction to Computer Science / Procedural – 67130
Generics 27-Nov-18.
CMSC 202 ArrayList Aug 9, 2007.
CMSC 202 ArrayList Aug 9, 2007.
slides created by Ethan Apter
Interator and Iterable
Object Oriented Programming
Java 5 New Features 1-May-19.
Generics 2-May-19.
Presentation transcript:

CompSci 100E 40.1 Java 5 New Features  Generics  Enhanced for loop  Autoboxing/unboxing  Typesafe enums  Other  Varargs  Static Import  Metadata  New classes and methods  VM Enhancements

CompSci 100E 40.2 Generics  Allows classes to store objects whose type is irrelevant to storing class, while allowing type-safe retrieval  E.g., Collection  Syntax ArrayList list = new ArrayList (); list.put(“hello”);// put() takes a String Iterator iter = list.iterator(); String s = iter.next();// next() returns a String  Compare with earlier Java ArrayList list = new ArrayList(); list.put(“hello”);// put() takes an Object Iterator iter = list.iterator(); String s = (String)iter.next(); // next() returns an Object which must be cast to String

CompSci 100E 40.3 Generics in API Docs  In API documentation, generics are given a type alias, e.g., “E”:  Alias is arbitrary, but stands for the same type throughout class definition  Can be on more than one type using different aliases  Examples  Class ArrayList o add(E o) o E get(int index)  Interface Map o V put(K key, V value) o V get(Object key) o Collection values()

CompSci 100E 40.4 Enhanced for Loop  Replaced iterators, indexing  Iterators and indexing are prone to bounds errors // throws ArrayIndexOutOfBoundsException for (int i = 0; i <= arr.length; i++) { System.out.println(arr[i]); } // what does this do? Iterator iter = list.iterator(); while (iter.hasNext()) { if (!“stop”.equals(iter.next())) { System.out.println(iter.next()); }

CompSci 100E 40.5 Looping in Java 5  Java 5 introduces new language syntax for looping over arrays and collections using for (aka “For-Each” loop)  Syntax: for (type var: collection) { // do something with var }  Examples: void processArray(String[] arr) { for (String s: arr) System.out.println(s.toUpperCase()); } // generics work with new for loop to simplify syntax! void processList(List list) { for (String s: list) System.out.println(s); }

CompSci 100E 40.6 Autoboxing/Unboxing  Java primitive types provided for performance, but mix poorly with objects: // compilation error! ArrayList list = new ArrayList(); list.add(42); int x = (int) list.get(0); // Kludgey fix provided by original Java: ugh! list.add(new Integer(42)); int x = ((Integer)list.get(0)).intValue()  Java 5 automatically “boxes” primitive types in Object types as neeeded: Integer objInt; objInt = 42;// equivalent to objInt = new Integer(42);

CompSci 100E 40.7 Autoboxing with Generics and For-Each  Note again how the new Java 5 features work together: // old syntax Integer sumInteger(List list) { int sum = 0; Iterator iter = list.iterator(); while (iter.hasNext()) { Integer iobj = (Integer) iter.next(); sum += iobj.intValue(); } return new Integer(sum); // new syntax Integer sumIntegers(List list) { int sum = 0; for (int x: list) sum+= x;// auto-unboxing elements return sum;// autobox return value }

CompSci 100E 40.8 New Features: Limitations  Generics are not everywhere, yet  consider list.toArray() returning Object[]  Enhanced for loop on non-parameterized collections is still annoying (obviously using generics helps, but what if you are forced to use legacy code?)  for (Object o: list) { String s = (String)o;... }  For loop doesn't give you a good way to loop over multiple collections in parallel:  still must do: int[] arr1, arr2; for (int i; i < arr1.length; i++) { int x = arr1[i] + arr2[i]; }

CompSci 100E 40.9 New Features: Limitations (con't)  Autoboxing doesn't carry over to arrays, or to converting arrays to lists and vice versa:  can't do the following: int[] arr = new int[100]; Integer[] arrInts = arr; List list = new ArrayList (); list.addAll(arr);

CompSci 100E Typesafe Enums  Enums are a safer alternative to constants  Old way: public static final int GO = 0; public static final int STOP = 1; public static final int YIELD = 2;....  Consider code taking these values as a parameter: void process(int status) { if (status == GO)... if (status == STOP)... if (status == YIELD)... else... // what does status == 10 mean?

CompSci 100E The Enum Alternative  Enums define a type, just like a class or primitive type  Enums are not interchangeable with ints, impossible to get undefined values  Enums can be enumerated using for  String representations of enums actually mean something  Examples: public enum TrafficLight { GO, STOP, YIELD } public TrafficLight myLight = STOP; for (TrafficLight t: TrafficLight.values()) { System.out.print(t); System.out.print(“ “); } // output: GO STOP YIELD

CompSci 100E Other New Features  Java 5 has many other new features, including:  Varargs – variable-size argument lists for methods  Static Import – import constants, e.g. Math.PI  Metadata – attach extra information about code  New classes and methods – Queue, Scanner, printf, etc.  VM Enhancements