1 CSC 2053 New from 5.0. 2 AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

Java Review Interface, Casting, Generics, Iterator.
Generics and the ArrayList Class
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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.
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.
Java Generics.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
P Object type and wrapper classes p Object methods p Generic classes p Interfaces and iterators Generic Programming Data Structures and Other Objects Using.
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.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
ArrayList, Multidimensional Arrays
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
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.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Types in programming languages1 What are types, and why do we need them?
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.
CS-2851 Dr. Mark L. Hornick 1 Generic Java Classes Implementing your own generic classes.
© 2004 Pearson Addison-Wesley. All rights reserved October 10, 2007 Parameter Lists & Command Line Arguments ComS 207: Programming I (in Java) Iowa State.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved5-2 Outline The if Statement and Conditions Other Conditional.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
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:
CSE 1201 Object Oriented Programming ArrayList 1.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
COS 312 DAY 12 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress report due Assignment corrected 1 MIA – 2 A’s, 2 B’s, 1 D, 1 F and 1 MIA – Code\pig.
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.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
© 2004 Pearson Addison-Wesley. All rights reserved October 5, 2007 Arrays ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
CMSC 202 ArrayList Aug 9, 2007.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Sixth Lecture ArrayList Abstract Class and Interface
Parameter Lists & Command Line Arguments
Chapter 20 Generic Classes and Methods
Loop Structures.
Java Programming Language
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
CMSC 202 ArrayList Aug 9, 2007.
Generics.
CMSC 202 ArrayList Aug 9, 2007.
Arrays October 6, 2006 ComS 207: Programming I (in Java)
Review: libraries and packages
Chapter 19 Generics.
Arrays.
Presentation transcript:

1 CSC 2053 New from 5.0

2 AutoBoxing

3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive types and the wrapper classes. The new autoboxing feature in J2SE 5.0 handles conversions -- for example, between values of type int and values of type Integer – in much more straightforward manner. Autoboxing can be used with assignment conversion and with wrapper class methods (e.g. Integer.parseInt()) If n is value of type int, then boxing converts n to an Integer object objN such that objN.intValue() is n

4 AutoBoxing Example: int m = 20, n; Integer objM = new Integer(10); Integer objN; objN = m; // autoboxing - converts m to an object n = objN; // unboxing – changes objN to an int // Expressions n = objM + 5; // unbox before addition objM++; // unbox before incrementing

5 Enhanced for loop

6 The Enhanced for Statement A for statement has the following syntax: for ( initialization ; condition ; increment ) statement; The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration

7 The pattern for processing elements of an ArrayList of Student objects called StudentList is : ArrayList StudentList = new ArrayList(); Student currentObject; for (int index = 0; index < StudentList.size(); index++) { currentObject = StudentList.get(index); // process currentObject } To perform the same operation with an enhanced for loop, for(Student currentObject:StudentList) { System.out.println(currentObject); } Where currentObject is a variable of Student

8 Enhanced For Loop // For loop – old way: ArrayList listofAutos = new ArrayList(); Auto currentAuto; for (int index = 0; index < listofAutos.size(); index++) { currentAuto = listofAutos.get(index); // process currentAuto } // For loop – new way: // Declare an object of an ArrayList of Autos called cars ArrayList cars = new ArrayList(); for (Auto currentAuto: cars) { // process currentAuto System.out.println(currentAuto);

9 public static void main( String [] args ) { ArrayList list = new ArrayList ( ); list.add( new Integer( 34 ) ); list.add( new Integer( 89 ) ); list.add( 65 ); // autoboxing System.out.println( "\nUsing the enhanced for loop:" ); for ( Integer currentInteger : list ) System.out.print( currentInteger + "\t" ); System.out.println( "\nUsing unboxing and enhanced for loop:" ); for ( int currentInt : list ) // unboxing System.out.print( currentInt + "\t" );

10 import java.util.ArrayList; public class Autoboxing { public static void main(String[] args) { ArrayList list = new ArrayList (); for(int i = 0; i < 10; i++) list.add(i); int sum = 0; for ( Integer j : list) sum += j; //unboxing for calculating System.out.printf("The sum is %d.", sum ); } First, ints are boxed to Integers as they are added to the ArrayList. Then Integers are unboxed to ints to be used in calculating the sum. Finally, the int representing the sum is boxed for use in the printf() statement.

11 Iterators and for Loops Recall that an iterator is an object that allows you to process each item in a collection A variant of the for loop simplifies the repetitive processing the items For example, if BookList is an iterator that manages Book objects, the following loop will print each book: for (Book myBook : BookList) System.out.println (myBook); Where Book is the name of the class and mybook is the object that will be used to iterate through it.

12 Iterators and for Loops This style of for loop can be read "for each Book in BookList, …" Therefore the iterator version of the for loop is sometimes referred to as the foreach loop It eliminates the need to call the hasNext and next methods explicitly.

13 Variable Length Parameter Lists

14 Variable Length Parameter Lists Suppose we wanted to create a method that processed a different amount of data from one invocation to the next For example, let's define a method called average that returns the average of a set of integer parameters // one call to average three values mean1 = average (42, 69, 37); // another call to average seven values mean2 = average (35, 43, 93, 23, 40, 21, 75);

15 Variable Length Parameter Lists We could define overloaded versions of the average method Downside: we'd need a separate version of the method for each parameter count We could define the method to accept an array of integers Downside: we'd have to create the array and store the integers prior to calling the method each time Instead, Java provides a convenient way to create variable length parameter lists

16 Variable Length Parameter Lists Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the same type For each call, the parameters are automatically put into an array for easy processing in the method public double average (int... list) { // whatever } element type array name Indicates a variable length parameter list

17 Variable Length Parameter Lists public double average (int... list) { double result = 0.0; if (list.length != 0) { int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; } return result; }

18 Variable Length Parameter Lists The type of the parameter can be any primitive or object type public void printGrades (Grade... grades) { for (Grade letterGrade : grades) System.out.println (letterGrade); }

19 Variable Length Parameter Lists A method that accepts a variable number of parameters can also accept other parameters The following method accepts an int, a String object, and a variable number of double values into an array called nums public void test (int count, String name, double... nums) { // whatever }

20 Generic Types

21 Generic Types Java enables us to define a class based upon a generic type This means that we can define a class so that it stores, operates on, and manages objects whose type is not specified until the class is instantiated. Assume that we need to define a class named Box that stores and manages other objects class Box { // declarations and code that manage // objects of type T }

22 Generic Types Then if we wanted to instantiate a Box to hold objects of the Widget class Box box1 = new Box But we could also instantiate a Box to hold objects of the Gadget class Box box2 = new Box

23 Generic Types The type supplied at the time of instantiation replaces the type T wherever it is used in the declaration of the class A generic type such as T cannot be instantiated Generics are used to develop collection classes

24 Generics One of the primary uses of generics is to abstract data types when working with collections. Prior to the JDK 5.0 release, when you created a Collection, you could put anything in it, for example: ArrayList myList = new ArrayList(10); myList.add(new Integer(10)); myList.add("Hello, World"); Since ArrayList takes any kind of object, if you wanted to restrict your Collection to a specific type, it was difficult at best. Getting items out of the collection required you to use a casting operation: Integer myInt = (Integer)myList.iterator().next();

25 Generics Previously, if you accidentally cast the wrong type, the program would successfully compile, but an exception would be thrown at runtime. Such an event could impair the reliability of the code. Generics allows you to specify, at compile-time, the types of objects you want to store in a Collection. The compiler can then check that the code is consistent with the specified code.

26 Generics Then when you add and get items from the list, the list knows what types of objects are supposed to be acted on. You don't need to cast anything. A Collection object is created with a specified type that dictates what type of element can be stored in it. The "<>" characters are used to designate what type is to be stored. If the wrong type of data is provided, a compile-time error is thrown. For example, if you try to compile the following class:

27 Generics public class First { public static void main(String args[]) { List myList = new ArrayList (10); myList.add(10); myList.add("Hello, World"); } } you get an error like this: First.java:7: cannot find symbol : method add(java.lang.String) location: interface java.util.List myList.add("Hello, World"); ^ 1 error

28 Generics This message basically says that there is no add(String) method available when the interface is for a List of Integer objects. The myList.add(10); method did add the Integer object of number 10 to the list. Autoboxing converted the int type to an Integer object. It is only the adding of a String to a List of Integer objects that failed here.

29 Generics If you look at the interface declaration for java.util.List, you see the following: public interface List extends Collection This literally says that it is declaring a List of E's. Later in the interface definition, you see methods where the argument or return type is replaced by an E: (or T) Iterator iterator(); ListIterator listIterator(); boolean add(E o); boolean addAll(Collection extends c);

30 When we invoke this with: List myList = new ArrayList (10); All of the E’s in the List interface are replaced by Integer. The E is a formal parameter and the Integer is the actual argument. The ? in the addAll line can be thought of as a collection of unknown, but the unknown would be E or a subclass. The question mark is called a wildcard. It is a supertype allowing you specify at creation the type you want to store. Generics

31 Generics Because the E is specified at compile time, you don't have to rely on runtime exceptions to find type mismatches. This construct allows you to work with collections of subclasses, and not simply exact matches.

32 Using bounds for Generic Types To check the type at compile time, we need to bind the generic type using the modifier : public static > max(T objA, T objB) { if(objA.compareTo(objB) > 0) return objA; else return objB; } Now the compiler flags with an error if any class is used which does not implement Comparable.

33 Generic Methods - Using Bounds We use bounding to ensure that the compiler will check the type arguments to see if they implement the Comparable interface. We bound the generic type using the modifier: > Extends is used rather than implements because this syntax can be used in an inheritance hierarchy for generic super classes and subclasses.

34 Wildcards To deal with generic classes and methods that could be passed either a superclass or subclass as a type argument, Java introduced wildcards. In this final version of max: public static > T max(T objA, T objB) { if(objA.compareTo(objB) > 0)) return objA; else return objB; }

35 Wildcards The tag ? in this final version of the max method, indicates that the type itself or some super class implements the Comparable interface The ? With bound “super T> directs the compiler to verify that either T or some super class of T implements Comparable. If this method compiles without a warning, it is then assuredly type safe.