COP 3503 FALL 2012 Shayan Javed Lecture 8

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

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
15-Jun-15 Lists in Java Part of the Collections Framework.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Copyright © Texas Education Agency, Advanced Computer Programming Data Structures: Collections.
1 ArrayList  Array’s are limited because we need to know the size before we use them.  An ArrayList is an extension of an array that grows and shrinks.
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.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
LinkedList Many slides from Horstmann modified by Dr V.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
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.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
CSE 1201 Object Oriented Programming ArrayList 1.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Object Oriented Programming in Java Habib Rostami Lecture 7.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
1 CS162: Introduction to Computer Science II Abstract Data Types.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Exposure Java 2011 APCS Edition
EKT472: Object Oriented Programming
CMSC 202 ArrayList Aug 9, 2007.
Using the Java Collection Libraries COMP 103 # T2
Sixth Lecture ArrayList Abstract Class and Interface
CompSci 230 S Programming Techniques
John Hurley Cal State LA
Data Structures Lakshmish Ramaswamy.
A tree set Our SearchTree class is essentially a set.
Implementing ArrayList Part 1
TCSS 143, Autumn 2004 Lecture Notes
Lecture 2: Implementing ArrayIntList reading:
ArrayLists.
Programming in Java Lecture 11: ArrayList
Data Type (how to view it)
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
(Java Collections Framework) AbstractSequentialList
A tree set Our SearchTree class is essentially a set.
CMSC 202 ArrayList Aug 9, 2007.
ArrayList Collections.
Chapter 19 Generics.
Chapter 21 Generics.
Chapter 24 Implementing Lists, Stacks, Queues, and Priority Queues
CMSC 202 ArrayList Aug 9, 2007.
Array Lists CSE 1310 – Introduction to Computers and Programming
ArrayLists 22-Feb-19.
Collections Framework
slides created by Marty Stepp
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
ArrayLists.
ArrayLists 27-Apr-19.
Chapter 21 Generics.
Web Design & Development Lecture 6
Chapter 19 Generics.
Java Generics & Iterators
Java Coding 6 David Davenport Computer Eng. Dept.,
Presentation transcript:

COP 3503 FALL 2012 Shayan Javed Lecture 8 Programming Fundamentals using Java

ArrayList and Java Generics

Collection A container object that groups multiple objects

Collection A container object that groups multiple objects Example: Arrays

Collection A container object that groups multiple objects Example: Arrays Java provides multiple classes/interfaces in the Java Collection Framework

Collection A container object that groups multiple objects Example: Arrays Java provides multiple classes/interfaces in the Java Collection Framework Going to look at ArrayList

Arrays Hold several elements (primitives/objects) of the same type

Arrays Hold several elements (primitives/objects) of the same type Size = static. Once set, cannot be changed

Arrays Advantages: Easy to access elements directly

Arrays Advantages: Easy to access elements directly Easy to traverse

Arrays Advantages: Disadvantages: Easy to access elements directly Easy to traverse Disadvantages: Have to decide on size before creating

Arrays Advantages: Disadvantages: Easy to access elements directly Easy to traverse Disadvantages: Have to decide on size before creating Inserting/removing elements is troublesome Shifting elements

ArrayList (java.util.ArrayList) Holds several objects in order (like Arrays)

ArrayList (java.util.ArrayList) Holds several objects in order (like Arrays) Unlike Arrays: Size does not need to be specified at creation time

ArrayList (java.util.ArrayList) Holds several objects in order (like Arrays) Unlike Arrays: Size does not need to be specified at creation time Grows in size as items added

ArrayList (java.util.ArrayList) Holds several objects in order (like Arrays) Unlike Arrays: Size does not need to be specified at creation time Grows in size as items added Provides useful methods for manipulating the list

ArrayList (java.util.ArrayList) Constructors: new ArrayList( ) - no need to pass in size (10)

ArrayList (java.util.ArrayList) Constructors: new ArrayList( ) - no need to pass in size (10) new ArrayList(int) - initial capacity

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index void clear(): Removes all elements

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index void clear(): Removes all elements boolean contains(Object o): Returns true if object is in the list

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index void clear(): Removes all elements boolean contains(Object o): Returns true if object is in the list Object get(int index): Returns object at the index

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index void clear(): Removes all elements boolean contains(Object o): Returns true if object is in the list Object get(int index): Returns object at the index boolean remove(Object o): Removes the object from the list

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index void clear(): Removes all elements boolean contains(Object o): Returns true if object is in the list Object get(int index): Returns object at the index boolean remove(Object o): Removes the object from the list Object remove(int index): Removes the object at the index

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index void clear(): Removes all elements boolean contains(Object o): Returns true if object is in the list Object get(int index): Returns object at the index boolean remove(Object o): Removes the object from the list Object remove(int index): Removes the object at the index int size(): Returns the no. of elements in the list

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index void clear(): Removes all elements boolean contains(Object o): Returns true if object is in the list Object get(int index): Returns object at the index boolean remove(Object o): Removes the object from the list Object remove(int index): Removes the object at the index int size(): Returns the no. of elements in the list int indexOf(Object o): Returns index of first matching element

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index void clear(): Removes all elements boolean contains(Object o): Returns true if object is in the list Object get(int index): Returns object at the index boolean remove(Object o): Removes the object from the list Object remove(int index): Removes the object at the index int size(): Returns the no. of elements in the list int indexOf(Object o): Returns index of first matching element Object set(int index, Object o): Sets the object at the index

ArrayList (java.util.ArrayList) Methods: boolean add(Object o): Appends object at the end of the list void add(int index, Object o): Inserts object at specified index void clear(): Removes all elements boolean contains(Object o): Returns true if object is in the list Object get(int index): Returns object at the index boolean remove(Object o): Removes the object from the list Object remove(int index): Removes the object at the index int size(): Returns the no. of elements in the list int indexOf(Object o): Returns index of first matching element Object set(int index, Object o): Sets the object at the index Object clone(): Returns a shallow copy

ArrayList Example import java.util.ArrayList;

ArrayList Example import java.util.ArrayList; ArrayList numbers = new ArrayList(); // no size specified initially

ArrayList Example import java.util.ArrayList; ArrayList numbers = new ArrayList(); // no size specified initially numbers.add(new Integer(10));

ArrayList Example import java.util.ArrayList; ArrayList numbers = new ArrayList(); // no size specified initially numbers.add(new Integer(10)); numbers.add(3); /* auto-boxing: converted to numbers.add(new Integer(3)); */

ArrayList Example import java.util.ArrayList; ArrayList numbers = new ArrayList(); // no size specified initially numbers.add(new Integer(10)); numbers.add(3); /* auto-boxing: converted to numbers.add(new Integer(3)); */ int sum = 0; // sum up all the numbers in the list int number = 0;

ArrayList Example import java.util.ArrayList; ArrayList numbers = new ArrayList(); // no size specified initially numbers.add(new Integer(10)); numbers.add(3); /* auto-boxing: converted to numbers.add(new Integer(3)); */ int sum = 0; // sum up all the numbers in the list int number = 0; for(int i = 0; i < numbers.size(); i++) { }

ArrayList Example import java.util.ArrayList; ArrayList numbers = new ArrayList(); // no size specified initially numbers.add(new Integer(10)); numbers.add(3); /* auto-boxing: converted to numbers.add(new Integer(3)); */ int sum = 0; // sum up all the numbers in the list int number = 0; for(int i = 0; i < numbers.size(); i++) { number = (Integer)numbers.get(i); // cast required – why? }

ArrayList Example import java.util.ArrayList; ArrayList numbers = new ArrayList(); // no size specified initially numbers.add(new Integer(10)); numbers.add(3); /* auto-boxing: converted to numbers.add(new Integer(3)); */ int sum = 0; // sum up all the numbers in the list int number = 0; for(int i = 0; i < numbers.size(); i++) { number = (Integer)numbers.get(i); // cast required – why? sum += number; // auto un-boxing: Integer converted to int }

ArrayList Example import java.util.ArrayList; ArrayList numbers = new ArrayList(); // no size specified initially numbers.add(new Integer(10)); numbers.add(3); /* auto-boxing: converted to numbers.add(new Integer(3)); */ numbers.add(“A String”); // will compile! int sum = 0; // sum up all the numbers in the list int number = 0; for(int i = 0; i < numbers.size(); i++) { number = (Integer)numbers.get(i); // cast required – why? sum += number; // auto un-boxing: Integer converted to int }

ArrayList Example import java.util.ArrayList; ArrayList numbers = new ArrayList(); // no size specified initially numbers.add(new Integer(10)); numbers.add(3); /* auto-boxing: converted to numbers.add(new Integer(3)); */ numbers.add(“A String”); // will compile! int sum = 0; // sum up all the numbers in the list int number = 0; for(int i = 0; i < numbers.size(); i++) { number = (Integer)numbers.get(i); // run-time error when i = 2 sum += number; // auto un-boxing: Integer converted to int }

How do we make sure we are dealing with objects of only one type? ArrayList How do we make sure we are dealing with objects of only one type?

ArrayList How do we make sure we are dealing with objects of only one type? Solution: Java Generics

Java Generics Generics is the capability to parameterize types

Java Generics Generics is the capability to parameterize types Can define class/interface/method with generic types – compiler replaces with concrete types.

Java Generics Generics is the capability to parameterize types Can define class/interface/method with generic types – compiler replaces with concrete types. Introduced in JDK 1.5

java.util.ArrayList<E> Methods: boolean add(E o): Appends object at the end of the list void add(int index, E o): Inserts object at specified index void clear(): Removes all elements boolean contains(E o): Returns true if object is in the list E get(int index): Returns object at the index boolean remove(E o): Removes the object from the list E remove(int index): Removes the object at the index int size(): Returns the no. of elements in the list int indexOf(E o): Returns index of first matching element E set(int index, E o): Sets the object at the index E clone(): Returns a shallow copy

Java Generics Type of objects it can hold is specified at declaration

Java Generics Type of objects it can hold is specified at declaration // will only hold Integer objects ArrayList<Integer> numbers = new ArrayList<Integer>();

ArrayList Example import java.util.ArrayList; ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(new Integer(10)); numbers.add(3); /* auto-boxing: */ numbers.add(“A String”); // WON’T COMPILE! int sum = 0; // sum up all the numbers in the list int number = 0; for(int i = 0; i < numbers.size(); i++) { number = (Integer)numbers.get(i); // cast NOT required – why? sum += number; // auto un-boxing: Integer converted to int }

ArrayList Example import java.util.ArrayList; ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(new Integer(10)); numbers.add(3); /* auto-boxing: */ numbers.add(“A String”); // WON’T COMPILE! int sum = 0; // sum up all the numbers in the list int number = 0; for(int i = 0; i < numbers.size(); i++) { number = numbers.get(i); // cast NOT required – why? sum += number; // auto un-boxing: Integer converted to int }

Java Generics More strictness

Java Generics More strictness Fewer errors

Generic Classes public class AClass<E> { // properties and methods can use the “E” type }

Generic Classes public class AClass<E> { // properties and methods can use the “E” type ArrayList<E> numbers = new ArrayList<E>(); }

Generic Methods public class GenericMethodDemo { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York”}; }

Generic Methods public class GenericMethodDemo { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York”}; } public static <E> void print(E[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }

Generic Methods public class GenericMethodDemo { public static void main(String[] args ) { Integer[] integers = {1, 2, 3, 4, 5}; String[] strings = {"London", "Paris", "New York”}; GenericMethodDemo.<Integer>print(integers); GenericMethodDemo.<String>print(strings); } public static <E> void print(E[] list) { for (int i = 0; i < list.length; i++) System.out.print(list[i] + " "); System.out.println(); }

Generic Interfaces public interface AnInterface<E> { // properties and methods can use the “E” type public void aMethod(E object); }

Generic Interfaces public interface Comparable<E> { public int compareTo(E object); }

Generic Interfaces public interface Comparable<E> { public int compareTo(E object); } public interface Comparator<E> { public int compare(E object1, E object2);

Generic Interfaces public Book implements Comparable{ // comparison based on price public int compareTo(Object o) { Book b = (Book)o; if (price > b.getPrice()) return 1; else if (price < b.getPrice()) return -1; else return 0; }

Generic Interfaces public Book implements Comparable{ // comparison based on price public int compareTo(Object o) { Book b = (Book)o; if (price > b.getPrice()) return 1; else if (price < b.getPrice()) return -1; else return 0; } } HOW WOULD YOU USE JAVA GENERICS?

Generic Interfaces public Book implements Comparable<Book>{ // comparison based on price public int compareTo(Book b) { Book b = (Book)o; if (price > b.getPrice()) return 1; else if (price < b.getPrice()) return -1; else return 0; }

Generic Interfaces public Book implements Comparable<Book>{ // comparison based on price public int compareTo(Book b) { Book b = (Book)o; // no more casting! if (price > b.getPrice()) return 1; else if (price < b.getPrice()) return -1; else return 0; }

Generic Interfaces public Book implements Comparable<Book>{ // comparison based on price public int compareTo(Book b) { Book b = (Book)o; // no more casting! if (price > b.getPrice()) return 1; else if (price < b.getPrice()) return -1; else return 0; }

Generic Interfaces public class ReviewComparison implements Comparator { public int compare (Object o1, Object o2) { Book b1 = (Book)o1; Book b2 = (Book)o2; if (b1.getACR() > b2.getACR()) return 1; if (b1.getACR() < b2.getACR()) return -1; else return 0; }

Generic Interfaces public class ReviewComparison implements Comparator<Book> { public int compare (Book b1, Book b2) { Book b1 = (Book)o1; Book b2 = (Book)o2; if (b1.getACR() > b2.getACR()) return 1; if (b1.getACR() < b2.getACR()) return -1; else return 0; }

Generic Interfaces public class ReviewComparison implements Comparator<Book> { public int compare (Book b1, Book b2) { Book b1 = (Book)o1; Book b2 = (Book)o2; if (b1.getACR() > b2.getACR()) return 1; if (b1.getACR() < b2.getACR()) return -1; else return 0; }

Java Generics - Summary Allows you to create a “general” template Classes/methods/interfaces Versatile and strict

Back to ArrayList... How does it work “behind the scenes”?

Back to ArrayList... How does it work “behind the scenes”? Elements are stored inside an array private array

Back to ArrayList... How does it work “behind the scenes”? Elements are stored inside an array private array Array has an initial capacity

Back to ArrayList... How does it work “behind the scenes”? Elements are stored inside an array private array Array has an initial capacity Empty constructor [new ArrayList()]: capacity 10

Back to ArrayList... How does it work “behind the scenes”? Elements are stored inside an array private array Array has an initial capacity Empty constructor [new ArrayList()]: capacity 10 Otherwise specify capacity [new ArrayList(capacity)]

ArrayList When number of elements exceeds capacity (the add/insert method):

ArrayList When number of elements exceeds capacity (the add/insert method): Internal array replaced by new one

ArrayList When number of elements exceeds capacity (the add/insert method): Internal array replaced by new one Elements from the old array copied over

ArrayList When number of elements exceeds capacity (the add/insert method): Internal array replaced by new one Elements from the old array copied over Insert and remove require shifting of elements

ArrayList When number of elements exceeds capacity (the add/insert method): Internal array replaced by new one Elements from the old array copied over Insert and remove require shifting of elements (Recall add/remove in Project1)

Efficiency of ArrayLists Reallocation of underlying array = when capacity reached and need to add more elements

Efficiency of ArrayLists Reallocation of underlying array = when capacity reached and need to add more elements Add/Insert/Remove = costly because requires shifting of elements in array

Efficiency of ArrayLists Reallocation of underlying array = when capacity reached and need to add more elements Add/Insert/Remove = costly because requires shifting of elements in array Accessing element (get) = fast just like an array

Efficiency of ArrayLists Reallocation of underlying array = when capacity reached and need to add more elements Add/Insert/Remove = costly because requires shifting of elements in array Accessing element (get) = fast just like an array Problems overcome with Linked Lists.

Other Java Collections LinkedList Stack Queue Will look at these later