The List Interface and ArrayLists

Slides:



Advertisements
Similar presentations
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
Advertisements

CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
15-Jun-15 Lists in Java Part of the Collections Framework.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
The Java Collections Framework By the end of this lecture you should be able to: use the ArrayList class to store a list of objects; use the HashSet class.
ArrayLists, LinkedLists, Collections Section 12.1.
List Interface and Linked List Mrs. Furman March 25, 2010.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
ArrayLists, LinkedLists, Collections Section 12.1.
CSE 143 Lecture 3 Implementing ArrayIntList reading: slides created by Marty Stepp and Hélène Martin
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
Slides by Donald W. Smith
EKT472: Object Oriented Programming
CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs)
Lecture 13: Interfaces, Comparable reading: , 16.4, 10.2
EECE 310: Software Engineering
CSE 373 Implementing a Stack/Queue as a Linked List
Building Java Programs
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Software Development Java Collections
Modern Collections Classes
A tree set Our SearchTree class is essentially a set.
Java Generics.
Top Ten Words that Almost Rhyme with “Peas”
Building Java Programs
Introduction to Collections
Introduction to Collections
TCSS 143, Autumn 2004 Lecture Notes
The ArrayList Class An ArrayList is a complex data structure that allows you to add or remove objects from a list and it changes size automatically. The.
Introduction to Collections
Building Java Programs
Lecture 26: Advanced List Implementation
Java Collections Framework
Arrays versus ArrayList
A tree set Our SearchTree class is essentially a set.
CSC 143 Queues [Chapter 7].
slides adapted from Marty Stepp
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
Building Java Programs
Dynamic Data Structures and Generics
Collections James Brucker.
Modern Collections Classes
slides created by Ethan Apter
Introduction to Collections
Collections Framework
slides created by Marty Stepp
Introduction to Collections
Introduction to Data Structure
More Data Structures (Part 1)
CSE 143 Lecture 3 Implementing ArrayIntList reading:
Data Structures & Algorithms
CSE 143 Lecture 4 Implementing ArrayIntList; Binary Search
slides created by Alyssa Harding
CSE 143 Lecture 2 ArrayIntList, binary search
Generics, Stack, Queue Based on slides by Alyssa Harding
slides created by Marty Stepp
List Interface ArrayList class implements the List Interface
CSE 143 Lecture 4 Implementing ArrayIntList reading:
Part of the Collections Framework
CSE 143 Lecture 21 Advanced List Implementation
Arrays and ArrayLists.
Implementing ArrayIntList
Introduction to Java Collection
slides created by Marty Stepp and Hélène Martin
Presentation transcript:

The List Interface and ArrayLists Section 12.1

Outcomes Use a List in place of an Array create an ArrayList or a LinkedList add, get, change, and remove elements loop thru it using for and for-each loops Loop thru a List using a ListIterator add and remove elements as you loop Recognize other kinds of Collections Use Collections class methods

Lists are for Listing Things What do you want to do with a list? add stuff to it print it out look to see what’s on it check how long it is check if some particular thing’s on it remove stuff from it List interface has methods for all those and lots more!

List ADT and Interface What is a list? sequence of things, all the same type (1st item, 2nd item, 3rd item, ..., last item) java.util.List interface is parameterized say what kind of objects are allowed on it list of Strings: List<String> myWords; list of Files: List<File> myFiles; list of integers: List<Integer> myNumbers; NOTE: List<int> is not allowed

List Data Types List is an interface Two kinds of List objects OK for variables List<String> var; but not for objects var = new List<String>(); Two kinds of List objects ArrayList var = new ArrayList<String>(); LinkedList var = new LinkedList<String>(); used exactly the same way! choose depending on what needs doing both from java.util

Side-by-Side List<String> list; list = new ArrayList<String>(); list.add("ten"); list.add("twenty"); list.add("thirty"); System.out.println(list); list.remove("twenty"); List<String> list; list = new LinkedList<String>(); list.add("ten"); list.add("twenty"); list.add("thirty"); System.out.println(list); list.remove("twenty"); [ten, twenty, thirty] [ten, thirty] [ten, twenty, thirty] [ten, thirty]

Creating a List and Adding to it Normal variable + new object declaration List<String> myWords = new ArrayList<String>(); List starts out empty 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” "Ten", "Fifteen", "Twenty" myWords "Ten", "Twenty" myWords myWords "Ten" myWords

List Objects Grow 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) Will grow as long as you keep adding that’s its length as long as it exists

Printing Out a List Lists can be printed directly! System.out (to screen) or a PrintWriter (to file) System.out.println("The list is " + myWords + "."); Output just like Arrays.toString(…) elements printed using their toString method The list is [Ten, Fifteen, Twenty].

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

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

Looking for Particular Items 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("It’s at location " + myWords.indexOf("Twenty") + "."); } We have a Twenty! It’s at location 2.

Looking for Particular Items 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! It’s at location 2. The location of the Hundred is -1.

Removing Stuff 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"); [Ten, Twenty] [Twenty]

Looping thru a List 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) They 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

Exercise Write a code fragment that reads a single line of words and adds them all to a List, then prints out the list Enter a line of words below: This is the line of words I entered. The words you entered were: [This, is, the, line, of, words, I, entered.]

Exercise Make this program using Lists N heats; top 2 advance What order did they finish in heat 1? Jill Anne Leslie Freida What order did they finish in heat 2? Carol Louisa Judith Annette What order did they finish in heat 3? Carla Giselle Lois Rachel What order did they finish in heat 4? Yvonne Darla Brenda The people who advanced are: [Jill, Anne, Carol, Louisa, Carla, Giselle, Yvonne, Darla] Not advancing were: [Leslie, Freida, Judith, Annette, Lois, Rachel, Brenda]

List Iterators To add or remove items while looping List Iterator goes thru list one item at a time like a Scanner going thru a file: next and hasNext can remove the item you just looked at can add item beside the one you just looked at Can also use it for changing items or just to look at the items

Creating a List Iterator Parameterized, just like List & ArrayList just ask the list for one ListIterator<String> it = allMyWords.listIterator(); no “new ListIterator<String>()” type needs to be the same as the List’s type "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it

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

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

ListIterators Can Go in Reverse Start at the last element use previous & hasPrevious public static void writeListReversed(List<String> list) { ListIterator<String> it = list.listIterator(list.size()); while(it.hasPrevious()) { System.out.println("\t" + it.previous()) } not as clumsy as the for loop version

Removing with an Iterator Going backwards is the same! while (it.hasPrevious()) { String word = it.previous(); if (word.startsWith("F")) it.remove(); } "Fifteen" word "Ten" word "Twenty" word "Fifty" word "Thirty" word "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it

Removing with an Iterator Which item did you just look at? That’s the one that gets removed. 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 Same as removing but we’re just changing instead of removing 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 Change words starting with F to upper case! while (it.hasPrevious()) { String word = it.previous(); if (word.startsWith("F")) it.set(word.toUpperCase()); } "Fifty" word "Thirty" word "Ten" word "Fifteen" word "Twenty" word "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords "FIFTEEN", "FIFTY" & it

Adding with an Iterator Adds towards the front of the list if going forward, then iterator will not see them if going backward. iterator will see them "Ten", "A", "Fifteen", "Twenty", "Thirty", "Fifty" "Ten", "A", "B", "Fifteen", "Twenty", "Thirty", "Fifty" "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" & it "Ten", "Fifteen", "Twenty", "Thirty", "A", "Fifty" "Ten", "Fifteen", "Twenty", "Thirty", "B", "A", "Fifty" "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" & it

Exercise Use an iterator to go thru a List<Integer>, removing every negative number and changing every 0 to a 42 go from front to back How would it change if we wanted to go from back to front?

List Interface More List interface methods isEmpty() check if list is empty clear() make list empty addAll(otherList) add all these containsAll(otherList) check if contains these removeAll(otherList) remove all these retainAll(otherList) keep only these subList(from, to) get part of the list

Check if a List is Empty Can use myList.size() == 0… but this is a bit easier and clearer S.o.p("List is now " + myList); if (myList.isEmpty()) S.o.p("My list is empty"); else S.o.p("My list isn’t empty"); List is now [Ten, Fifteen, Twenty, Thirty, Fifty] My list isn’t empty

Clear a List Make this list empty again removes every element from the list if (myList.isEmpty()) S.o.p("My list is empty"); else S.o.p("My list isn’t empty"); myList.clear(); if (myList.isEmpty()) S.o.p("Now my list is empty"); else S.o.p("My list still isn’t empty"); My list isn’t empty Now my list is empty

Add Elements from Another List For adding many elements at once combine two lists S.o.p("Section A: " + sectionA); S.o.p("Section B: " + sectionB); List<String> combined = new ArrayList<String>(); combined.addAll(sectionA); combined.addAll(sectionB); S.o.p("Combined: " + combined); Section A: [Bill, Carol, Laura] Section B: [Ann, Don, Ed, Fran] Combined: [Bill, Carol, Laura, Ann, Don, Ed, Fran]

Check for Several Elements Are these all there or not? S.o.p("Combined: " + combined); if (combined.containsAll(sectionA)) S.o.p("All section A’s in the combined list"); if (sectionA.containsAll(combined)) S.o.p("Everyone from the combined list is in section A"); else S.o.p("Someone in the combined list is not in section A"); Combined: [Bill, Carol, Laura, Ann, Don, Ed, Fran] All section A’s in the combined list Someone from the combined list is not in section A

Remove Multiple Elements Take these away, if they’re there no problem if they’re not there S.o.p("Combined: " + combined); sectionA.add("Gil"); S.o.p ("Section A: " + sectionA); combined.removeAll(sectionA); S.o.p ("Combined: " + combined); Combined: [Bill, Carol, Laura, Ann, Don, Ed, Fran] Section A: [Bill, Carol, Laura, Gil] Combined: [Ann, Don, Ed, Fran]

Retain Multiple Elements Keep only these, if they’re there no problem if they’re not there S.o.p("Combined: " + combined); List<String> keepers = new LinkedList<String>(); keepers.add("Ann"); keepers.add("Bill"); keepers.add("Louise"); keepers.add("Ed"); combined.retainAll(keepers); S.o.p ("Combined: " + combined); Combined: [Ann, Don, Ed, Fran] Combined: [Ann, Ed]

Getting Parts of Lists Choose first element of list (by position), and first element not on the list (by position) List<String> letters = new ArrayList<String>(); letters.add("b"); letters.add("i"); letters.add("e"); letters.add("y"); letters.add("o"); S.o.p("Letters: " + letters); S.o.p("Letters 1 to 3:" + letters.subList(1, 3)); Letters: [b, i, e, y, o] Letters 1 to 3: [i, e]

Sublists Actually part of the larger list (not a copy) Select part of the list [b, i, e, y, o] letters.subList(1, 3)  [i, e] Actually part of the larger list (not a copy) can be used to modify parts of the list letters.subList(1, 3).set(1, "x"); [b, i, x, y, o] letters.subList(1, 3).clear(); [b, y, o] b i e y o 1 2 3 4 5 1 2 b i e x y o 1 2 3 4 5

Exercise Recall the race program from last time Add drugs testing: several heats, top 2 runners advance Add drugs testing: get a list of runners failing their drug tests disqualify them from advancing what method do we use?

the Collection interface List interface extends Collection interface Collection is an object that holds other objects Collections have base types (<String>, ...) Sets are another kind of Collection as are Queues Collection<E> List<E> Set<E> Queue<E> Collection, List, Set & Queue are interfaces; ArrayList & LinkedList are classes ArrayList<E> LinkedList<E>

Collection Methods Common to Lists, Sets and Queues add(T), remove(T), clear() contains, equals, isEmpty, size, toArray addAll, containsAll, removeAll, retainAll hashCode, iterator List and Deque add several methods different methods for each Set adds no more methods

Lists vs. Sets List elements allow duplicates; Sets do not list1 [a, b, c, a, b, d, a, a, a, a, b, z] set1 [a, b, c, d, z] Client puts List elements in order; computer chooses order for Set elements list1.add("e"); [a, b, c, a, b, d, a, a, a, a, b, z, e] set1.add("e"); [a, b, c, d, e, z] Set interface implemented by (e.g.) TreeSet

the Collections class the Collections (note the s) class has several static methods for working with Collection objects (like ArrayLists) Collection is an interface implemented by class such as ArrayList Collections is a class has methods that are useful for Collection objects (such as an ArrayList)

Sorting Lists You can write your own sorting method... using insertion sort, merge sort, quick sort, ... ...or you can use sort from Collections import java.util.Collections; ... Collections.sort(words); sorts into lexicographic order

Sorting into Alphabetical Order sort can be told to use a different order for example, to ignore case Collections.sort(words, String.CASE_INSENSITIVE_ORDER); the list to sort comes first, the comparator next a comparator is an object that lets you compare two other objects – in this case Strings you can create your own comparators by implementing the Comparator interface

Other Collections Methods Collections.methodName(args..); frequency(list, 10)  2 [10, 20, 10, 5] max(list)  20 [10, 20, 10, 5] min(list)  5 [10, 20, 10, 5] reverse(list) [5, 10, 20, 10] replaceAll(list, 10, 7) [5, 7, 20, 7] swap(list, 0, 2) [20, 7, 5, 7] shuffle(list) maybe [7, 20, 5, 7] max & min can also take comparators as 2nd argument

Exercise Write a method that shows how many of each element is in a List<Integer> – but only in the range of the elements in the list for example: [10, 5, 10, 3, 5, 10, 22, 19, 10, 5] 3 appears 1 time(s) 4 appears 0 time(s) 5 appears 3 time(s) ... 22 appears 1 time(s)

Questions