Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.

Slides:



Advertisements
Similar presentations
Review Generics and the ArrayList Class
Advertisements

Generics and the ArrayList Class
The Fundamental Rule for Testing Methods Every method should be tested in a program in which every other method in the testing program has already been.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
© 2006 Pearson Addison-Wesley. All rights reserved16-1 Iterators An iterator is an object that is used with a collection to provide sequential access to.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 101 Dynamic Data Structures and Generics Chapter 10.
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 24 : Collections King Fahd University of Petroleum & Minerals College of Computer.
Iterators in Java. Lecture Objectives To understand the concepts of Java iterators To understand the differences between the Iterator and ListIterator.
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.
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.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
1 More on Arrays Arrays of objects Command line arguments The ArrayList class Javadoc Review Lecture 8 notes and L&L 7.1 – 7.2 Reading for this lecture:
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
Java Unit 9: Arrays Declaring and Processing Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
ArrayList, Multidimensional Arrays
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Programming With Java ICS201 1 Chapter 14 Generics and The ArrayList Class.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
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.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
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.
Chapter 101 Dynamic Data Structures and Generics Chapter 10.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
The ArrayList Data Structure Standard Arrays at High Speed!
Chapter 9 Introduction to Arrays Fundamentals of Java.
Java Generics. Lecture Objectives To understand the objective of generic programming To be able to implement generic classes and methods To know the limitations.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
CMSC 202 ArrayList Aug 9, 2007.
Lecture 10 Collections Richard Gesick.
Sixth Lecture ArrayList Abstract Class and Interface
John Hurley Cal State LA
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Copying ArrayLists Copied Section of
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
CMSC 202 ArrayList Aug 9, 2007.
CS2013 Lecture 4 John Hurley Cal State LA.
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
Classes, Objects and Methods
Arrays.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Using ArrayList

Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class

The ArrayList Class ArrayList 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 In general, an ArrayList serves the same purpose as an array, except that an ArrayList can change length while the program is running

The class ArrayList is implemented using an array as a private instance variable  When this hidden array is full, a new larger hidden array is created and the data is transferred to this new array The ArrayList Class (Cont’d)

Why not always use an ArrayList instead of an array? 1.An ArrayList is less efficient than an array. 2.It does not have the convenient square bracket notation. 3.The base type of an ArrayList must be a class type (or other reference type): it cannot be a primitive type. This last point is less of a problem now that Java provides automatic boxing and unboxing of primitives. The ArrayList Class (Cont’d)

Using the ArrayList Class In order to make use of the ArrayList class, it must first be imported from the package java.util 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 ();

An initial capacity can be specified when creating an ArrayList as well  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);  Specifying an initial capacity does not limit the size to which an ArrayList can eventually grow. Note that the base type of an ArrayList is specified as a type parameter Using the ArrayList Class (Cont’d)

The add method is used to set an element for the first time in an ArrayList: list.add("something");  The method name add is overloaded.  There is also a two argument version that allows an item to be added at any currently used index position or at the first unused position Using the ArrayList Class (Cont’d)

The size method is used to find out how many indices already have elements in the ArrayList int howMany = list.size(); The set method is used to replace any existing element, and the get method is used to access the value of any existing element list.set(index, "something else"); String thing = list.get(index); Using the ArrayList Class (Cont’d)

Tip: Adding to an ArrayList The add method is usually used to place an element in an ArrayList position for the first time (at an ArrayList index). The simplest add method has a single parameter for the element to be added, and adds an element at the next unused index, in order. An element can be added at an already occupied list position by using the two-parameter version of add. This causes the new element to be placed at the index specified, and every other member of the ArrayList to be moved up by one position.

The two-argument version of add can also be used to add an element at the first unused position (if that position is known). Any individual element can be changed using the set method.  However, set can only reset an element at an index that already contains an element In addition, the method size can be used to determine how many elements are stored in an ArrayList. Tip: Adding to an ArrayList (Cont’d)

Class ArrayList: Methods The tools for manipulating arrays consist only of the square brackets and the instance variable length. 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

Class ArrayList: Methods (Cont’d) import java.util.*; public class TestArrayList1 { public static void main(String[] args) { ArrayList arr1 = new ArrayList (10); ArrayList arr2 = new ArrayList (); }

Class ArrayList: Methods (Cont’d)

import java.util.*; public class TestArrayList2 { public static void main(String[] args) { ArrayList arr1 = new ArrayList (10); System.out.println(arr1); arr1.add(“Ahmed”); arr1.add(“Khaled”); arr1.add(“Ali”); System.out.println(arr1); arr1.set(0, “Fahad”); System.out.println(arr1); } 1 2 3

Class ArrayList: Methods (Cont’d)

Differences of Parameter Types When 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 This is because the ArrayList class implements a number of interfaces, and inherits methods from various ancestor classes  These interfaces and ancestor classes specify that certain parameters have type Object

The "For Each" Loop The ArrayList class is an example of a collection class Starting 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 )

The "For Each" Loop: An Example

The "For Each" Loop: An Example (Cont’d) Program Output:

Using ArrayList: An Example

Program Output:

Using trimToSize to Save Memory An 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 If 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

The clone method Makes a Shallow Copy! When a deep copy of an ArrayList is needed, using the clone method is not sufficient:  Invoking clone on an ArrayList object produces a shallow copy, not a deep copy. In order to make a deep copy, it must be possible to make a deep copy of objects of the base type.  Then a deep copy of each element in the ArrayList can be created and placed into a new ArrayList object.

The Vector Class The Java standard libraries have a class named Vector that behaves almost exactly the same as the class ArrayList In most situations, either class could be used  However the ArrayList class is newer, and is becoming the preferred class

Nonparameterized ArrayList and Vector Classes The ArrayList and Vector classes discussed here have a type parameter for the base type. There are also ArrayList and Vector classes with no parameter whose base type is Object.  These classes are left over from earlier versions of Java.