ArrayLists, LinkedLists, Collections Section 12.1.

Slides:



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

BUILDING JAVA PROGRAMS CHAPTER 10.1 ARRAY LISTS. 22 OBJECTIVES! Use ArrayList to construct and analyze lists of arbitrary length.
Week 2: Primitive Data Types 1.  Programming in Java  Everything goes inside a class  The main() method is the starting point for executing instructions.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
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.
Building Java Programs
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
Lists in Python.
Week 2 - Monday.  What did we talk about last time?  Software development  Lab 1.
(c) University of Washington14-1 CSC 143 Java Collections.
ARRAYLIST.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
1 CSC 221: Computer Programming I Spring 2008 ArrayLists and arrays  example: letter frequencies  autoboxing/unboxing  ArrayLists vs. arrays  example:
ArrayList, Multidimensional Arrays
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
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.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
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.
CS1101: Programming Methodology
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
More Methods and Arrays Material from Chapters 5 to 7 that we didn’t cover in 1226.
Week 14 - Monday.  What did we talk about last time?  Inheritance.
Simple Arrays Arrays of primitives and Strings Sections 7.1, 7.2.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
ArrayLists (and the for-each loop) ArrayList example = new ArrayList (); example.add(4);
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
List Interface and Linked List Mrs. Furman March 25, 2010.
Chapter 5 Linked List by Before you learn Linked List 3 rd level of Data Structures Intermediate Level of Understanding for C++ Please.
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.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Grouping objects Arrays. 2 Fixed-size collections The maximum collection size may be pre-determined with an upper limit Array is an fixed-size collection.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
ArrayLists, LinkedLists, Collections Section 12.1.
The ArrayList Data Structure Standard Arrays at High Speed!
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Exceptions Chapter 9.
(like an array on steroids)
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Week 14 - Wednesday CS 121.
CS 106A, Lecture 19 ArrayLists
CS Week 9 Jim Williams, PhD.
Arrays versus ArrayList
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
CMSC 202 ArrayList Aug 9, 2007.
Can store many of the same kind of data together
Object Oriented Programming in java
The List Interface and ArrayLists
slides created by Alyssa Harding
Review: libraries and packages
Arrays and ArrayLists.
Throwing, Catching Defining
Why not just use Arrays? Java ArrayLists.
Java Coding 6 David Davenport Computer Eng. Dept.,
Presentation transcript:

ArrayLists, LinkedLists, Collections Section 12.1

Outcomes n Create and use an ArrayList  add, get, change, and remove elements  loop thru it using for and for-each loops n Replace an array with an ArrayList n Loop thru an ArrayList using a ListIterator  add and remove elements as you loop n Create and use a LinkedList n Recognize other kinds of Collections

Lists n What is a list?  sequence of things, all the same type  (1 st item, 2 nd item, 3 rd item,..., last item) n We have used arrays for lists  arrays are not ideal for representing lists »need to say at start how big it is »can’t change its size n There are better ways....

Lists are for Listing Things n What do you want to do with a list?  add values to it  print it out  look to see what’s on it  check how long it is  check if some particular value’s on it  remove values from it n Java has a couple of types for this

ArrayLists n Class java.util.ArrayList uses an array  but provides methods to make using it easier n ArrayList is a parameterized type  say what kind of things are allowed on it  base class goes inside  base class goes inside »list of Strings:ArrayList myWords; »list of Files:ArrayList myFiles; »list of integers:ArrayList myNumbers;  NOTE: ArrayList is not allowed

Creating a List and Adding to it n Normal variable + new object declaration ArrayList myWords = new ArrayList ();  the list starts out empty n Add method to add items (to end of list) myWords.add(“Ten”);myWords.add(“Twenty”);  can also say where to add to the list myWords.add(1, “Fifteen”); »skip over 1 item, then add “Fifteen” myWords "Ten" myWords "Ten", "Twenty" myWords "Ten", "Fifteen", "Twenty" myWords

List Objects Grow n List objects start empty  not like array objects »array has a length when you create it »array elements are initialized (to 0 if nothing else) n Will grow as long as you keep adding  not like array objects »array has a length when you create it »that’s its length as long as it exists

Compiler Warnings n If when you compile you get this warning: then you forgot to put the (or whatever) somewhere ArrayList words = new ArrayList();  find where the mistake is and fix it »recompile with –Xlint:unchecked to see where »or just look/search Note: CompilerWarning.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. JCreator & NetBeans may already compile with Xlint:unchecked

Printing Out a List n Lists can be printed the usual way!  System.out (to screen) or a PrintWriter (to file) »not like arrays! System.out.println(“The list is ” + myWords + “.”); n Output is a single line with brackets and commas  elements of list are printed as usual The list is [Ten, Fifteen, Twenty].

Getting List Elements n Lists use zero-based indexing  just like arrays String firstWord = myWords.get(0); System.out.println(“The first word is ” + firstWord + “.”); The list is [Ten, Fifteen, Twenty]. The first word is Ten. "Ten", "Fifteen", "Twenty" myWords "Ten" firstWord

Checking its Length n Method called size instead of length  not like arrays int size = myWords.size(); System.out.println(“Last is ” + myWords.get(size-1) + “.”); The list is [Ten, Fifteen, Twenty]. The first word is Ten. Last is Twenty. "Ten", "Fifteen", "Twenty" myWords 3 size

Looking for Particular Items n Is it there at all? contains  Where exactly is it? indexOf if (myWords.contains(“Twenty”)) { System.out.println(“We have a Twenty!”); } System.out.println(“The Twenty’s location is ” + myWords.indexOf(“Twenty”) + “.”); We have a Twenty! The Twenty’s location is 2.

Looking for Particular Items n Is it there at all? contains  Where exactly is it? indexOf if (myWords.contains(“Hundred”)) { System.out.println(“We have a Hundred!”); } System.out.println(“The location of the Hundred is ” + myWords.indexOf(“Hundred”) + “.”); We have a Twenty! The Twenty’s location is 2. The location of the Hundred is -1.

Removing Stuff n What thing to remove, or which position?  int argument  remove from that position myWords.remove(1);System.out.println(myWords);  object argument  remove that object myWords.remove(“Ten”);System.out.println(myWords); [Ten, Twenty] [Twenty]

Changing List Elements n Use the set method to change a value  give the location and the new value myWords.set(0, “Thirty”); System.out.println(“The list is now” + myWords + “.”); The list is now [Thirty].

Looping thru a List n Multiple ways to loop thru a list  can use the usual for loop for (int i = 0; i < myWords.size(); i++)  can use this simplified for loop (for-each loop) for (String word : myWords) n These work if you’re just looking at the list  can cause trouble if you’re adding or removing from the list at the same time!

Usual for Loop for (int i = 0; i < allMyWords.size(); i++) { System.out.println(“\t” + i + “) ” + allMyWords.get(i)); } “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords 0) Ten 1) Fifteen 2) Twenty 3) Thirty 4) Fifty

Simplified for Loop for (String word : allMyWords) { System.out.println(“\t” + word); } “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords Ten Fifteen Twenty Thirty Fifty

Arrays vs. ArrayLists // create the array String[] arr = new String[N]; // fill in its values for (int i = 0; i < N; i++) { arr[i] = kbd.next(); arr[i] = kbd.next();} // change a value arr[2] = arr[2] + “!!!”; // print its elements one per line for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); System.out.println(arr[i]);} // create the list ArrayList list = new ArrayList (); // fill in its values for (int i = 0; i < N; i++) { list.add(kbd.next()); list.add(kbd.next());} // change a value list.set(2, list.get(2) + “!!!”); // print its elements one per line for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); System.out.println(list.get(i));}

Why Use Array(List)s? n ArrayLists are better if:  don’t know how many elements are needed  will be adding/removing list elements n Arrays are better if:  you know how many elements you’ll need »or a good upper bound  you won’t be adding/removing elements except at the end

In Particular... n When reading from a file, you often don’t know how many elements there will be  use an ArrayList instead of an array n Loop until file ends, adding elements while (fin.hasNext()) { myWords.add(fin.next());}  reads all the words of that file into myWords  don’t need to check for filled array

“Wrapper” Classes n Can’t use primitive types in an ArrayList  ArrayList, ArrayList,... n But every primitive type has a wrapper  int  Integer  double  Double  char  Character  boolean  Boolean n Use the wrapper class instead

Arrays vs. ArrayLists (Primitive) // create the array double[] arr = new double[N]; // fill in its values for (int i = 0; i < N; i++) { arr[i] = kbd.nextDouble(); arr[i] = kbd.nextDouble();} // change a value arr[2] = 3.14 * arr[2]; // print its elements one per line for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); System.out.println(arr[i]);} // create the list ArrayList list = new ArrayList (); // fill in its values for (int i = 0; i < N; i++) { list.add(kbd.nextDouble()); list.add(kbd.nextDouble());} // change a value list.set(2, 3.14 * list.get(2)); // print its elements one per line for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); System.out.println(list.get(i));}

Reading All Numbers from a File n Loop until no more numbers  remember to use wrapper class ArrayList myNumbers = new ArrayList (); Scanner fin = new Scanner(new File(fileName)); while (fin.hasNextDouble()) { myNumbers.add(fin.nextDouble()); myNumbers.add(fin.nextDouble());}fin.close(); »(still need to catch/declare FileNotFoundException)

Exercise n Revise this code to read integer values instead of doubles ArrayList myNumbers = new ArrayList (); Scanner fin = new Scanner(new File(fileName)); while (fin.hasNextDouble()) { myNumbers.add(fin.nextDouble()); myNumbers.add(fin.nextDouble());}fin.close();

Important Reminder! n Don’t add/remove el t s in for/foreach loop  you will get some kind of a mistake... »see ModificationError.java ...or program will crash »see ModificationCrash.java »java.util.ConcurrentModificationException »(don’t catch this kind of exception!) n Use a java.util.ListIterator instead

List Iterators n To add or remove items while looping  List Iterator goes thru list one item at a time import java.util.ListIterator; »like a Scanner going thru a file: next and hasNext while (it.hasNext()) { System.out.println(it.next()); }  can remove the item you just looked at  can add item beside the one you just looked at n Can also use it for changing items  or just to look at the items

Creating a List Iterator n Parameterized, just like ArrayList  ask the list for one–so it knows which list to use ListIterator it = allMyWords.listIterator(); »no “new ListIterator ()”  type needs to be the same as the List’s type “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it

Looping thru the List n hasNext: is there is another item? n next: get the next item (and advance) while (it.hasNext()) { System.out.println(it.next());} “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it Ten Fifteen Twenty Thirty Fifty

next and hasNext n It’s just next and hasNext  NOT nextInt, nextDouble, …  even if it’s an ArrayList of Integers or Doubles ArrayList dl = new ArrayList (); ListIterator it = dl.listIterator(); double num = 0; if (it.hasNextDouble()) { num = it.nextDouble(); num = it.nextDouble();} cannot find symbol method hasNextDoublecannot find symbol method nextDouble

Removing with an Iterator n Example: Delete items that start with “F” while (it.hasNext()) { String word = it.next(); if (word.startsWith(“F”)) it.remove();} “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it “Ten” word “Fifteen” word “Twenty” word “Thirty” word “Fifty” word

Removing with an Iterator n Which item did you just look at? n That’s the one that gets removed. n General policy  check to see if there is a next/previous  save the next/previous into a variable  check the variable to see if it needs removed  if so, use the iterator’s remove method to remove it

Changing with an Iterator n Like removing  change the item we just looked at n General policy  check to see if there is a next/previous  save the next/previous into a variable  check the variable to see if it needs changed  if so, use the iterator’s set method to change it

Changing with an Iterator n Example: Allcaps items that start with “F” while (it.hasNext()) { String word = it.next(); if (word.startsWith(“F”)) it.set(word.toUpperCase());} “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords & it “FIFTEEN”,, “FIFTY” “Ten” word “Fifteen” word “Twenty” word “Thirty” word “Fifty” word

Adding with an Iterator n Like removing  add where the iterator is “pointing” »new item is “previous” to the iterator n General policy  check to see if there is a next/previous  save the next/previous into a variable  check the variable to see if we need to add  if so, use the iterator’s add method to add a new value

Adding with an Iterator n Ex.: Duplicate items that start with “F” while (it.hasNext()) { String word = it.next(); if (word.startsWith(“F”)) it.add(word.toLowerCase());} “Ten”, “Fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords word “Ten” word “Fifteen” word “Twenty” word “Thirty” word “Fifty” word & it “Ten”, “Fifteen”, “fifteen”, “Twenty”, “Thirty”, “Fifty” allMyWords “Ten”, “Fifteen”, “fifteen”, “Twenty”, “Thirty”, “Fifty”, “fifty” allMyWords

Exercise n Use an iterator to go thru a List, removing every negative number and changing every 0 to a 42  do it as two loops: »loop #1 removes every negative # »loop #2 changes every 0 to a 42  do it as one loop »what’s common between the two loops above?

Some Other ArrayList Methods n list.methodName(args...);  isEmpty()check if list is empty  clear()make list empty  addAll(otherList)add all these  containsAll(otherList)check if has all these  removeAll(otherList)remove all these  retainAll(otherList)keep only these  subList(from, to)get part of the list »it doesn’t make a copy; it gives you part of the list

Exercise n If list1 is [Alex, Betty, Carol, David], and list2 is [Andrew, Betty, Chris], then what is list1 after list1.addAll(list2)?  (Same values), after list1.removeAll(list2)?  (Same values), after list1.retainAll(list2)?  (Same values), after list1.clear()?  (Same values), what’s list1.containsAll(list2)?  (Same values), what’s list1.subList(2, 4)?

Other Lists n LinkedList is another kind of List  use it just like an ArrayList LinkedList words = new LinkedList (); while(fin.hasNext()) { list.add(fin.next()); }  does exactly the same things, but... »it’s more efficient at add/remove »it’s less efficient at get/set  use whichever one is better for your program »it’s an empirical question! try both ways.

Other Collections n Sets  sets do not allow duplicates »add a duplicate  command ignored  computer decides what order to keep them in »usually sorted, but not necessarily!  java.util.HashSet, java.util.TreeSet,...  use when you only care if it’s there/not-there n Also Deques, Queues

The Collections Class n The java.util.Collections class has methods for dealing with Collections import java.util.Collections; n Example: sort your list with this command: Collections.sort(myList);  or this one (for alphabetical order) Collections.sort(words, String.CASE_INSENSITIVE_ORDER);

Things Collections Can Do n Collections.methodName(args..); .max(list)  20[10, 20, 10, 5, 8] .min(list)  5[10, 20, 10, 5, 8] .reverse(list)[8, 5, 10, 20, 10] .replaceAll(list, 10, 7)[8, 5, 7, 20, 7] .swap(list, 0, 2)[7, 5, 8, 20, 7] .shuffle(list)maybe [7, 20, 5, 7, 8]

Exercise n If list1 is [50, 19, 21, 44, 18, 21], then what is Collections.max(list1)?  Collections.max(list1)?  Collections.min(list1)?  list1 after Collections.reverse(list1)?  list1 after Collections.sort(list1)?  list1 after Collections.swap(list1, 1, 3)?  list1 after Collections.replaceAll(list1, 0, 21)? »careful – it’s a bit of a trick question!

Questions? n Next Week  review for second test  second test »File I/O »Exceptions »ArrayLists