19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

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.
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.
Problem Solving # 9: ArrayList, Collections and More ICS
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
15-Jun-15 Lists in Java Part of the Collections Framework.
For use of Cleveland State's IST410 Students only 1 Vectors and Collections.
25-Jun-15 Vectors. 2 Vectors and arrays A Vector is like an array of Object s Differences between arrays and Vector s: Arrays have special syntax; Vector.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Vectors. Vectors and arrays A Vector is like an array of Object s Differences between arrays and Vector s: –Arrays have special syntax; Vector s don’t.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
1 ADTs, Collection, Iterable/Iterator Interfaces Collections and the Java Collections API The Collection Interface and its Hierarchy The Iterable and Iterator.
12-Jul-15 Lists in Java Part of the Collections Framework.
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.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
Arrays And ArrayLists - S. Kelly-Bootle
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
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.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
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.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
ArrayList, Multidimensional Arrays
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
Copyright 2008 by Pearson Education Building Java Programs ArrayList Reading: 10.1.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
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.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
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.
© 2006 Pearson Addison-Wesley. All rights reserved5 B-1 Chapter 5 (continued) Linked Lists.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
Week111 APCS-A: Java Arrays Continued (related information in Chapter 7 of Lewis & Loftus) November 16, 2005.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
EKT472: Object Oriented Programming
COP 3503 FALL 2012 Shayan Javed Lecture 8
Implementing ArrayList Part 1
TCSS 143, Autumn 2004 Lecture Notes
ArrayLists.
Programming in Java Lecture 11: ArrayList
Generics 27-Nov-18.
ArrayList Collections.
ArrayLists 22-Feb-19.
Collections Framework
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
ArrayLists.
ArrayLists 27-Apr-19.
Generics 2-May-19.
ArrayList.
Web Design & Development Lecture 6
Part of the Collections Framework
Arrays and ArrayLists.
Presentation transcript:

19-Mar-16 Collections and ArrayLists.

2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists. Loading ArrayLists. Some important ArrayList Methods.

3 Why Collections? Object-Oriented programs often require defining classes that are collections of objects of another class. Provinces are collections of Counties. Orders are collections of Items. Units are collections of soldiers. Polygons are collections of points. They enable the representation of a one-to-many relationship.

4 Collections and Implementations. Collections contain elements. Collections have operations in common but may be implemented differently. Some collections are better for searching and some better for processing elements sequentially. In a production environment, you should choose your collections carefully based on advantages and disadvantages. We will only deal with ArrayLists.

5 Collection: Common operations in the Java Collection Library int size( ); boolean isEmpty( ); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator( ); //Traverse the collection.

6 Common Operation in a User System Collection Example : Province ….County Possible Methods. addCounty( County county ). Add a county to the collection. removeCounty( County county ). removeCounty( int index ). removeCounty ( String countyName). iterator getCounties(). We need an object which allows us to go through the entire collection of counties. store( String filename). Store contents to named file. load( String filename). Load contents from named file.

7 Generics In Java versions 1.4 and earlier, an ArrayList just held Object s, which could be of any (non-primitive) type For compatibility reasons you can still do this, but you will get a lot of warning messages In Java 5 you should specify the class of objects that the ArrayList will hold This is done with the new generics syntax

8 Creating a ArrayList the old way The syntax for creating ArrayList s has changed between Java 1.4 and Java 5 For compatibility reasons, the old way still works, but will give you warning messages Here are the (old) constructors: import java.util.ArrayList; //Important ArrayList vec1 = new ArrayList(); Constructs an ArrayList with an initial capacity of 10 ArrayList vec2 = new ArrayList( initialCapacity );

9 Using an ArrayList the old way boolean add(Object obj ) Appends the object obj to the end of this ArrayList Example: myArrayList.add("A string is an object"); Object get(int index ) Returns the component at position index Note that this is returned as an Object ; to use it as a String, you must cast it Example: String s = (String)myArrayList.get(5);

10 Creating a ArrayList the new way Specify, in angle brackets after the name, the type of object that the class will hold Examples: ArrayList vec1 = new ArrayList (); ArrayList vec2 = new ArrayList (10); To get the old behavior, but without the warning messages, use the wildcard Example: ArrayList vec1 = new ArrayList ();

11 Adding elements to a ArrayList boolean add(Object obj ) Appends the object obj to the end of this ArrayList With generics, the obj must be of the correct type, or you get a compile-time (syntax) error Always returns true This is for consistency with other, similar classes void add(int index, Object element ) Inserts the element at position index in this ArrayList The index must be greater than or equal to zero and less than or equal to the number of elements in the ArrayList With generics, the obj must be of the correct type, or you get a compile-time (syntax) error

12 Removing elements boolean remove(Object obj ) Removes the first occurrence of obj from this ArrayList Returns true if an element was removed Uses equals to test if it has found the correct element void remove(int index ) Removes the element at position index from this ArrayList void clear() Removes all elements

13 Accessing with and without generics Object get(int index ) Returns the component at position index Using get the old way: ArrayList myList = new ArrayList(); myList.add("Some string"); String s = (String)myList.get(0); Using get the new way: ArrayList myList = new ArrayList (); myList.add("Some string"); String s = myList.get(0); Notice that casting is no longer necessary when we retrieve an element from a “genericized” ArrayList

14 Searching a ArrayList boolean contains(Object element ) Tests if element is a component of this ArrayList Uses equals to test if it has found the correct element int indexOf(Object element ) Returns the index of the first occurrence of element in this ArrayList Uses equals to test if it has found the correct element Returns -1 if element was not found in this ArrayList int lastIndexOf(Object element ) Returns the index of the last occurrence of element in this ArrayList Uses equals to test if it has found the correct element Returns -1 if element was not found in this ArrayList

15 Getting information boolean isEmpty() Returns true if this ArrayList has no elements int size() Returns the number of elements currently in this ArrayList Object[ ] toArray() Returns an array containing all the elements of this ArrayList in the correct order

16 More about equals There are many different notions of equality Example: two sets are equal if they contain the same elements; order of elements is irrelevant Java defines public boolean equals(Object) in the Object class, but equals is defined to be the same as == It’s often a good idea to override equals for your own objects If you do this, note that the argument should be a general Object The String class (and some others) override equals

17 ArrayList Sample 1 import java.util.*; public class ArrayListGenericDemo { public static void main(String[] args) { ArrayList data = new ArrayList (); data.add("hello"); data.add("goodbye"); // data.add(new Date()); This won't compile! Iterator it = data.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s); } } }

18 Your turn. Write a program that declares a ArrayList of strings and do the following: Load the ArrayList with the strings; “Toronto”, “Montreal”, “Vancouver”, “Frankfurt”. Search for the string “Frankfurt” and print an appropriate message. Remove the city, “Frankfurt” then search for “Frankfurt” again and print an appropriate message.

19 Iterating through an ArrayList Use an iterator: Use the hasNext() to test for end of list. Use the next() to get and use the object. Use the size() and get() methods to iterate through the ArrayList using a for. Use a for…each.

20 iterators import java.util.*; ArrayList data = new ArrayList ();. // load with elements. Iterator it = data.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s); } Get an iterator From ArrayList Loop until hasNext fails Get and use Next element

21 Iterating using size() and get() import java.util.*; ArrayList data = new ArrayList ();. // load with elements. for(int i=0; i < data.size(); i++) { String s = data.get( i); System.out.println(s); } size() gives you number of elements in ArrayList Get by index.

22 Iterating using a for:each import java.util.*; ArrayList data = new ArrayList ();. // load with elements. for(String element:data ) { System.out.println(element); } Declare a variable of same type as ArrayList elements to represent current element in list Use variable. In processing

23 Your Turn! Write a program which will create an ArrayList of strings then load it with the strings “L6L1M6”, ”M6N3F5”,”L6K6T2”,”V7TL5T”,”V7TL5T”, “M4F3T5”. Using an iterator traverse the list and remove any string representing a Vancouver postal code (begins with V). After processing the ArrayList in this manner, use a for..each to display the contents of the ArrayList using System.out.println();