Programming With Java ICS201 1 Chapter 14 Generics and The ArrayList Class.

Slides:



Advertisements
Similar presentations
Generics and the ArrayList Class
Advertisements

Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 23 : Generics King Fahd University of Petroleum & Minerals College of Computer Science.
Generics and The ArrayList Class
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
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.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Chapter 7: User-Defined Methods
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.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
ArrayList, Multidimensional Arrays
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
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.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
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.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
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:
Interfaces and Inner Classes
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
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.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
CMSC 202 ArrayList Aug 9, 2007.
Java Generics.
Sixth Lecture ArrayList Abstract Class and Interface
Lecture 5: Some more Java!
Java Generics.
CMSC 202 Generics.
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
CMSC 202 ArrayList Aug 9, 2007.
Dynamic Data Structures and Generics
Comp 249 Programming Methodology
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
slides created by Ethan Apter
CMSC 202 Generics.
Review: libraries and packages
Chapter 19 Generics.
Arrays.
Presentation transcript:

Programming With Java ICS201 1 Chapter 14 Generics and The ArrayList Class

Programming With Java ICS201 2 Part 1 The ArrayList Class

Programming With Java ICS201 3 The ArrayList Class oArrayList is a class in the standard Java libraries.  Unlike arrays, which have a fixed length once they have been created, an ArrayList is an object that can grow and shrink while your program is running. oIn general, an ArrayList serves the same purpose as an array, except that an ArrayList can change length while the program is running.

Programming With Java ICS201 4 ArrayLists Disadvantages An ArrayList is less efficient than an array. It does not have the convenient square bracket notation. The base type of an ArrayList must be a class type (or other reference type): it cannot be a primitive type (int, double, or char).

Programming With Java ICS201 5 Using the ArrayList Class o In order to make use of the ArrayList class, it must first be imported from the package java.util. o An ArrayList is created and named in the same way as object of any class, except that you specify the base type as follows: ArrayList aList = new ArrayList (); o An initial capacity can be specified when creating an ArrayList as well.  e.g. The following code creates an ArrayList that stores objects of the base type String with an initial capacity of 20 items. ArrayList list = new ArrayList (20);

Programming With Java ICS201 6 The ArrayList Methods o The tools for manipulating arrays consist only of the square brackets and the instance variable length. o ArrayLists, however, come with a selection of powerful methods that can do many of the things for which code would have to be written in order to do them using arrays.

Programming With Java ICS201 7 The ArrayList Methods Example: ArrayList list1 = new ArrayList (30); ArrayList list2 = new ArrayList ();

Programming With Java ICS201 8 The ArrayList Methods Example: ArrayList list = new ArrayList (); int index = 2; …… list.set(index, “Here”); String S = list.get(index);

Programming With Java ICS201 9 The ArrayList Methods Example: ArrayList list = new ArrayList (); list.add(“Java”); list.add(“Course”); list.add(0,“Semester 081”);

Programming With Java ICS The ArrayList Methods

Programming With Java ICS The ArrayList Methods

Programming With Java ICS The ArrayList Methods

Programming With Java ICS The ArrayList Methods

Programming With Java ICS The ArrayList Methods

Programming With Java ICS The ArrayList Methods

Programming With Java ICS Why are Some Parameters of Type Base_Type and Others of type Object oWhen looking at the methods available in the ArrayList class, there appears to be some inconsistency.  In some cases, when a parameter is naturally an object of the base type, the parameter type is the base type.  However, in other cases, it is the type Object. oThis is because the ArrayList class implements a number of interfaces, and inherits methods from various classes.  These interfaces and classes specify that certain parameters have type Object.

Programming With Java ICS For-each Loop for ArrayList Objects oThe ArrayList class is an example of a collection class. oStarting with version 5.0, Java has added a new kind of for loop called a for-each or enhanced for loop.  This kind of loop has been designed to cycle through all the elements in a collection (like an ArrayList).  Syntax: for (Array_Base_Type Variable : ArrayList_Object) Statement  Example: ArrayList list = new ArrayList (10); for (Integer element : list) element = 20 ;

Programming With Java ICS Use trimToSize to Save Memory oAn ArrayList automatically increases its capacity when needed.  However, the capacity may increase beyond what a program requires.  In addition, although an ArrayList grows automatically when needed, it does not shrink automatically. oIf an ArrayList has a large amount of excess capacity, an invocation of the method trimToSize will shrink the capacity of the ArrayList down to the size needed.

Programming With Java ICS Example (ArrayList class) import java.util.*; class ArrayListDemo { public static void main(String[] args) { ArrayList list = new ArrayList (20); list.add("AB") ; list.add("CD") ; list.add("GH") ; list.add("IJ") ; list.add("KL") ; list.add("MN") ; list.add("QR") ; list.add("ST") ; list.add("WX") ; list.add("YZ") ; // Print the elements of the ArrayList System.out.println("The following is the initial ArrayList:"); for(String s : list) System.out.print(s +" "); // Add elements to the ArrayList list.add(2, "ef") ; list.add(7, "op") ; list.add(10, "uv") ; // Print the new ArrayList System.out.println(" "); System.out.println("The following is the new ArrayList:"); for(String s : list) System.out.print(s +" "); continued

Programming With Java ICS Example (ArrayList class) // Print the element at position index1 in the ArrayList System.out.println(" "); int index1=11; String element = list.get(index1) ; System.out.println("The element at position " +" " +index1 +" " +"is" +" " +element); // Print the index of an element of the ArrayList System.out.println(" "); int index = list.indexOf("CD") ; System.out.println("The element CD is at position " +" “ +index); } Output: The following is the initial ArrayList: AB CD GH IJ KL MN QR ST WX YZ The following is the new ArrayList: AB CD ef GH IJ KL MN op QR ST uv WX YZ The element at position 11 is WX The element BC is at position 1

Programming With Java ICS Parameterized Classes and Generics oThe class ArrayList is a parameterized class. oIt has a parameter, denoted by Base_Type, that can be replaced by any reference type to obtain a class for ArrayLists with the specified base type. oStarting with version 5.0, Java allows class definitions with parameters for types.  These classes that have type parameters are called parameterized class or generic definitions, or, simply, generics.

Programming With Java ICS Part 2 Generics

Programming With Java ICS Generics o Classes and methods can have a type parameter:  A type parameter can have any reference type (i.e., any class type) plugged in for the type parameter.  When a specific type is plugged in, this produces a specific class type or method.  Traditionally, a single uppercase letter is used for a type parameter, but any non-keyword identifier may be used.

Programming With Java ICS Generics o A class definition with a type parameter is stored in a file and compiled just like any other class. o Once a parameterized class is compiled, it can be used like any other class.  However, the class type plugged in for the type parameter must be specified before it can be used in a program.  Doing this is said to instantiate the generic class Sample object = new Sample ( );

Programming With Java ICS Example (Generics) public class Sample { private T data ; public void setData(T newData) { data = newData ; } T is a parameter for a type public T getData( ) { return data ; } } o The class Sample could be used as follows: Sample object = new Sample ( ) ; Object.setData(“Hello”) ; System.out.println(object.getData( ) ) ;

Programming With Java ICS Class Definition with a Type Parameter o A class that is defined with a parameter for a type is called a generic class or a parameterized class.  The type parameter is included in angular brackets after the class name in the class definition heading.  Any non-keyword identifier can be used for the type parameter, but by convention, the parameter starts with an uppercase letter.  The type parameter can be used like other types used in the definition of a class.

Programming With Java ICS Example (A Generic Class for Ordered Pairs) public class Pair { private T first; private T second; public Pair() { first = null; second = null; } public Pair(T firstItem, T secondItem) { first = firstItem; second = secondItem; } public void setFirst(T newFirst) { first = newFirst; } public void setSecond(T newSecond) { second = newSecond; } public T getFirst() { return first; } public T getSecond() { return second; } }

Programming With Java ICS Example (A Generic Class for Ordered Pairs) public class GenericPairDemo { public static void main(String[] args) { Pair secretPair = new Pair ("Happy", "Day"); Scanner obj = new Scanner(System.in); System.out.println("Enter two words:"); String word1 = obj.next(); String word2 = obj.next(); Pair inputPair = new Pair (word1, word2); if (word1 == secretPair.getFirst() && word2 == secretPair.getSecond()) { System.out.println("You guessed the secret words"); System.out.println("in the correct order!"); } else { System.out.println("You guessed incorrectly."); System.out.println("You guessed"); System.out.println(inputPair); System.out.println("The secret words are"); System.out.println(secretPair); } Output: Enter two words: two words You guessed incorrectly. You guessed first: two second: words The secret words are first: Happy second: Day

Programming With Java ICS A Generic Constructor Name Has No Type Parameter o Although the class name in a parameterized class definition has a type parameter attached, the type parameter is not used in the heading of the constructor definition: public Pair () // Illegal o A constructor can use the type parameter as the type for a parameter of the constructor, but in this case, the angular brackets are not used: public Pair(T first, T second) // legal o When a generic class is instantiated, the angular brackets are used: Pair pair = new Pair ("Happy", "Day");

Programming With Java ICS A Primitive Type Cannot be Plugged in for a Type Parameter o The type plugged in for a type parameter must always be a reference type.  It cannot be a primitive type such as int, double, or char.  However, now that Java has automatic boxing, this is not a big restriction.  Note: reference types can include arrays.

Programming With Java ICS A Type Parameter Cannot Be Used Everywhere a Type Name Can Be Used o Within the definition of a parameterized class definition, there are places where an ordinary class name would be allowed, but a type parameter is not allowed. o In particular, the type parameter cannot be used in simple expressions using new to create a new object.  For instance, the type parameter cannot be used as a constructor name or like a constructor: T object = new T(); // the first T is legal // the second one is illegal T[] a = new T[10]; // the first T is legal // the second one is illegal

Programming With Java ICS An Instantiation of a Generic Class Cannot be an Array Base Type o Arrays such as the following are illegal: Pair [] a = new Pair [10];  Although this is a reasonable thing to want to do, it is not allowed given the way that Java implements generic classes.

Programming With Java ICS A Class Definition Can Have More Than One Type Parameter o A generic class definition can have any number of type parameters.  Multiple type parameters are listed in angular brackets just as in the single type parameter case, but are separated by commas.

Programming With Java ICS Example (Using a Generic Class With two Type Parameters) public class Pair { private T1 first; private T2 second; public Pair() { first = null; second = null; } public Pair(T1 firstItem, T2 secondItem) { first = firstItem; second = secondItem; } public void setFirst(T1 newFirst) { first = newFirst; } public void setSecond(T2 newSecond) { second = newSecond; } public T1 getFirst() { return first; } public T2 getSecond() { return second; } }

Programming With Java ICS Example (A Generic Class for Ordered Pairs) public class GenericPairDemo2 { public static void main(String[] args) { Pair Pair1 = new Pair (“major2 Grade", 15); Scanner obj = new Scanner(System.in); System.out.println("Enter your expected grade:"); int Grade = obj.nextInt(); Pair Pair2 = new Pair (“major2 Grade", Grade); if (Grade == Pair1.getSecond()) { System.out.println("You got the expected grade"); System.out.println("You got " +Pair1.getSecond() +" " +"out of 20"); } else { System.out.println("You did not get the expected grade"); System.out.println("You got " +Pair1.getSecond() +" " +"out of 20"); } Output: Enter your expected grade: 12 You did not get the expected grade You got 15 out of 20

Programming With Java ICS A Generic Class Cannot Be an Exception Class o It is not permitted to create a generic class with Exception, Error, Throwable, or any descendent class of Throwable.  A generic class cannot be created whose objects are throwable public class GEx extends Exception // Illegal  The above example will generate a compiler error message.

Programming With Java ICS Bounds For Type Parameters o Sometimes it makes sense to restrict the possible types that can be plugged in for a type parameter T.  For instance, to ensure that only classes that implement the Comparable interface are plugged in for T, define a class as follows: public class RClass  "extends Comparable" serves as a bound on the type parameter T.  Any attempt to plug in a type for T which does not implement the Comparable interface will result in a compiler error message.

Programming With Java ICS Bounds For Type Parameters o A bound on a type may be a class name (rather than an interface name).  Then only descendent classes of the bounding class may be plugged in for the type parameters public class ExClass o A bounds expression may contain multiple interfaces and up to one class. o If there is more than one type parameter, the syntax is as follows: public class Two

Programming With Java ICS Example (Bounds For Type Parameters) public class Pair { private T first; private T second; public T max() { if (first.compareTo(second) <= 0) return first ; else return second ; }

Programming With Java ICS Generic Interfaces o An interface can have one or more type parameters. o The details and notation are the same as they are for classes with type parameters.

Programming With Java ICS Generic Methods o When a generic class is defined, the type parameter can be used in the definitions of the methods for that generic class. o In addition, a generic method can be defined that has its own type parameter that is not the type parameter of any class.  A generic method can be a member of an ordinary class or a member of a generic class that has some other type parameter.  The type parameter of a generic method is local to that method, not to the class.

Programming With Java ICS Generic Methods o The type parameter must be placed (in angular brackets) after all the modifiers, and before the returned type. public static T genMethod(T[] a) o When one of these generic methods is invoked, the method name is prefaced with the type to be plugged in, enclosed in angular brackets. String s = NonG. genMethod(c);

Programming With Java ICS Inheritance With Generic Classes o A generic class can be defined as a derived class of an ordinary class or of another generic class.  As in ordinary classes, an object of the subclass type would also be of the superclass type. o Given two classes: A and B, and given G: a generic class, there is no relationship between G and G  This is true regardless of the relationship between class A and B, e.g., if class B is a subclass of class A