ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.

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

Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Building Java Programs
1 CSE 143 Lecture 1: ArrayList reading: Welcome to CSE 143! I'm Allison Obourn
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
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
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Copyright 2008 by Pearson Education Building Java Programs Chapter 10 Lecture 10-1: ArrayList reading: 10.1.
1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية.
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.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
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.
CSE 143 Lecture 2 ArrayList reading: 10.1 slides created by Marty Stepp
Copyright 2010 by Pearson Education Building Java Programs Chapter 10 Lecture 21: ArrayList reading: 10.1.
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 4 Exceptions and ArrayList slides created by Marty Stepp
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.
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.
Building Java Programs Chapter 10 ArrayList Copyright (c) Pearson All rights reserved.
CMSC 202 ArrayList Aug 9, 2007.
slides created by Marty Stepp
Sixth Lecture ArrayList Abstract Class and Interface
Collections.
Collections.
(like an array on steroids)
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Building Java Programs
Week 2: 10/1-10/5 Monday Tuesday Wednesday Thursday Friday
Welcome to CSE 143!.
Building Java Programs
Building Java Programs Chapter 10
TCSS 143, Autumn 2004 Lecture Notes
Lecture 2: Implementing ArrayIntList reading:
ArrayLists.
Programming in Java Lecture 11: ArrayList
Building Java Programs
Building Java Programs
CSE 143 Lecture 4 ArrayList Reading: 10.1.
ArrayLists.
Building Java Programs Chapter 10
Words exercise Write code to read a file and display its words in reverse order. A solution that uses an array: String[] allWords = new String[1000]; int.
CSE 143 Lecture 1 Arrays (review); ArrayList reading: 10.1
CMSC 202 ArrayList Aug 9, 2007.
Building Java Programs
CSE 143 Lecture 1 Arrays (review); ArrayList reading: 10.1
Chapter 10 ArrayList reading: 10.1
CSE 143 Lecture 2 Collections and ArrayIntList
Welcome to CSE 143!.
Lecture 1: ArrayList reading: 10.1
Lecture 2: Implementing ArrayIntList reading:
Welcome to CSE 143! Go to pollev.com/cse143.
CMSC 202 ArrayList Aug 9, 2007.
Building Java Programs
slides created by Ethan Apter
Lecture 13: ArrayLists AP Computer Science Principles
Lecture 16: Arraylist Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
CSE 143 Lecture 3 Implementing ArrayIntList reading:
ArrayLists.
Parsing JSON, Using Libraries, Java Collections, Generics
slides created by Marty Stepp
Building Java Programs
slides created by Marty Stepp
CSE 143 Lecture 1 Arrays (review); ArrayList reading: 10.1
Presentation transcript:

ARRAYLIST.. Hazen High School

Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper Class Boxing Unboxing Comparable Comparison function Natural Ordering

What ? Resizable Array [Automatic] Allows Duplication. Order - Maintains Insertion order. Type Safety Capacity and Size

Array List The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold

Array Lists an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk

Methods and Fields ArrayList list = new ArrayList() Assignment / Insertion list.Add(“Item1”); // Syntax : list.add( ) Size : int arrayListLength = list.Size(); Retrieval : String firstString = list.get(0); // Syntax : list.get( ) Removal : list.Remove(0) // Syntax : list.Remove( ) Others IsEmpty(), Clear(), ToArray(), Set(Index, Object) See full reference list at end of the slide deck.

Generics - Type Parameters ArrayList name = new ArrayList (); — When constructing an ArrayList, you must specify the type of elements it will contain between. — This is called a type parameter or a generic class. — Allows the same ArrayList class to store lists of different types. ArrayList names = new ArrayList (); names.add(“Kory Srock”); names.add(“Tod Oney”);

Generics Using different classes in Collection. Why ? Better programmability Better Object Orientation Example ArrayList myList = new ArrayList(); ArrayList a = new ArrayList () ArrayList list = new ArrayList ()

Array Vs ArrayList Grows automatically Work well with Generics ArrayList stringArrayList = new ArrayList (); Objects vs References Pass by Value --- Pass by Reference

ArrayList of primitives? The type you specify when creating an ArrayList must be an object type; it cannot be a primitive type. // illegal -- int cannot be a type parameter ArrayList list = new ArrayList (); But we can still use ArrayList with primitive types by using special classes called wrapper classes in their place. // creates a list of ints ArrayList list = new ArrayList ();

Wrapper classes A wrapper is an object whose sole purpose is to hold a primitive value. Once you construct the list, use it with primitives as normal: PrimitiveWrapper intType IntegerType double Double char Character boolean Boolean ArrayList grades = new ArrayList (); grades.add(3.2); grades.add(2.7);... double myGrade = grades.get(0

ArrayList versus Array – Code Examples Construction String[] names = new String[5]; ArrayList list = new ArrayList (); Storing a value names[0] = "Michael"; list.add("Michael"); Retrieving a value String s = names[0]; String s = list.get(0);

ArrayList vs Array – Code Examples Continued Doing something to each value that starts with "B" for (int i = 0; i < names.length; i++) { if (names[i].startsWith("B")) {... }} for (int i = 0; i < list.size(); i++) { if (list.get(i).startsWith("B")) {... } } Seeing whether the value "Nathaniel" is found for (int i = 0; i < names.length; i++) { if (names[i].equals("Nathaniel")) {... }} if (list.contains("Nathaniel")) {... }

Objects storing collections An object can have an array, list, or other collection as a field. public class Course { private double[] grades; private ArrayList studentNames; public Course() { grades = new double[4]; studentNames = new ArrayList ();... } Now each object stores a collection of data inside it. This is called “composition” (the collection is a component)

Exercise #1 Write a method addStars that accepts an array list of strings as a parameter and places a * after each element. — Example: if an array list named list initially stores: [the, quick, brown, fox] — Then the call of addStars(list); makes it store: [the, *, quick, *, brown, *, fox, *] Write a method removeStars that accepts an array list of strings, assuming that every other element is a *, and removes the stars (undoing what was done by addStars above).

Questions ArrayList list = new ArrayList() list.Add(“Item1”); list.Add(“Item2”); Will this compile ? Yes, assuming declaration of import java.util.ArrayList;

Questions.. Cntd.. ArrayList list = new ArrayList() list.Add(“1”); list.Add(“2”); list.Add(3); Will this compile ? Yes, all are added as objects

Questions.. Cntd.. ArrayList list = new ArrayList(3) list.Add(“1”); list.Add(“2”); list.Add(“3”); list.Add(“4”); Will this compile ? Yes. ArrayList grows dynamically

Questions.. Cntd.. ArrayList list = new ArrayList(4) list.Add(“1”); list.Add(“2”); list.Add(“4”); System.out.println(list.indexOf(“2”)); Will this compile ? Output ? Yes, it will compile Output is 1

Questions.. Cntd.. ArrayList list = new ArrayList(4); list.add(“1”); list.add(“2”); list.add(“4”); for(int i=0;i<5;i++) System.out.println(list.get(i)); Will this compile ? Output ? No, IndexOutOfBoundsException What do we need to do to fix it? Change for loop to 4 instead of 5

Question.. Tricky ArrayList arr1 = new ArrayList(); ArrayList arr2 = arr1; arr1.Add("Test"); System.out.println(arr1.Length == arr2.Length); Compile? Output ? ArrayList arr1 = new ArrayList(); ArrayList arr2 = new ArrayList(); arr1.Add("Test"); arr2.Add(arr1.get(0)); arr1[0] = “Test1”; System.out.println(arr2.get(0)); Compile? Output ? No, there is no method.length for arraylists, need to use.size What is the output once we change.length to.size? true Won’t compile – arr1[0]= “Test1” is a array type conflict What do we need to do to fix it? Arr1.add(“Test1”)

import java.util.*; class ArrayListDemo { public static void main(String args[]) { ArrayList al = new ArrayList(); // create an array list System.out.println("Initial size of al: " + al.size()); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " +al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } Initial size of al: 0 Size of al after additions: 7 Contents of al: [C, A2, A, E, B, D, F] Size of al after deletions: 5 Contents of al: [C, A2, E, B, D] What is the initial size of al? What is the size of al after additions? What is the contents of al? What is the size after deletions?

Exercise #2 Use Array List to implement the following exercise Create and Display a List of Employees in a Company with each Employee information containing the following Id Name Date of Birth Designation Address Skill Sets [ Accounts, Sales, Marketing, IT, Support, Management, Delivery ] List of products worked [ ProjectX, PriojectY, ProjectZ, ProjectH ] Each Project should track the list of Employees in it Each Dept./Skill Sets should track the list of Employees in it Hint : Use Static variables to track the List of Employees and Count of them in Project / Department

Array List Methods add(value) appends value at end of list add(index, value) inserts given value just before the given index, shifting subsequent values to the clear() right removes all elements of the list indexOf(value) returns first index where given value is found in list (-1 if not found) get(index) returns the value at given index remove(index) removes/returns value at given index, shifting subsequent values to the left set(index, value) replaces value at given index with given size() value returns the number of elements in list toString() returns a string representation of the list such as "[3, 42, -7, 15]"

Array List Methods Continued addAll(list) addAll(index, list) adds all elements from the given list to this list (at the end of the list, or inserts them at the given contains(value) index) returns true if given value is found somewhere in containsAll(list) this list returns true if this list contains every element from equals(list) given list returns true if given other list contains the same iterator() listIterator() elements returns an object used to examine the contents of the list (seen later) lastIndexOf(value) returns last index value is found in list (-1 if not remove(value) found) finds and removes the given value from this list removeAll(list) removes any elements found in the given list from retainAll(list) this list removes any elements not found in given list from subList(from, to) this list returns the sub-portion of the list between indexes from (inclusive) and to (exclusive) toArray() returns the elements in this list as an array

PracticeIt University+of+Washington+CSE+143%2FCS2+Exams%2 FCS2+Midterm+Exams%2F143+Practice+Midterm+5&pro blem=143practicemidterm5-ArrayListMystery University+of+Washington+CSE+143%2FCS2+Exams%2 FCS2+Midterm+Exams%2F143+Practice+Midterm+5&pro blem=143practicemidterm5-ArrayListMystery

Question.. Tricky ArrayList arr1 = new ArrayList(); ArrayList arr2 = arr1.clone(); arr1.Add("Test"); arr2.Add(arr1.get(0)); arr1[0] = “Test1”; System.Out.PrintLn(arr2.get(0)); Output ? ArrayList arr1 = new ArrayList(); ArrayList arr2 = new ArrayList(); arr1.Add("Test"); arr2.Add(arr1.get(0).Clone()); arr1[0] = “Test1”; System.Out.PrintLn(arr2.get(0)); Output ?