63
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others. CS 106A, Lecture 19 ArrayLists suggested reading: Java Ch. 11.8

CS 106A, Lecture 19 ArrayLists - web.stanford.edu · This document is copyright (C) ... CS 106A, Lecture 19 ArrayLists suggested reading: Java Ch. 11.8. 2 ArrayLists HashMaps

Embed Size (px)

Citation preview

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

CS106A,Lecture19ArrayLists

suggestedreading:JavaCh.11.8

2

ArrayListsHashMaps

Wearehere

3

Learning Goals• KnowhowtostoredatainandretrievedatafromanArrayList.

4

Plan for today•Recap:Tic-Tac-Toe•ArrayLists•Example:reversiblewriting•Example:planner•ArrayLists vs.arrays•Recap

5

Plan for today•Recap:Tic-Tac-Toe•ArrayLists•Example:reversiblewriting•Example:planner•ArrayLists vs.arrays•Recap

6

Tic-Tac-ToeLet’suse2DarraystocreateaConsoleProgram versionofTic-Tac-Toe.

7

Plan for today•Recap:Tic-Tac-Toe•ArrayLists•Example:reversiblewriting•Example:planner•ArrayLists vs.arrays•Recap

8

Limitations of Arrays• Sizemustbespecifieduponcreation• Can’tadd/remove/insertelementslater• Nobuilt-inmethodsforsearching,etc.• Can’tprintarrayswithoutArrays.toString (orArrays.deepToString)

index 0 1 2 3 4 5 6 7 8 9

value 12 49 -2 26 5 17 -6 84 72 3

9

Introducing… ArrayLists!•Avariabletypethatrepresentsalistofitems.•Youaccessindividualitemsbyindex.•Storeasingletypeofobject(String,GRect,etc.)•Resizable– canaddandremoveelements•Hashelpfulmethodsforsearchingforitems

10

Our First ArrayList

ArrayList<String> myArrayList = new ArrayList<>();

11

Our First ArrayList

ArrayList<String> myArrayList = new ArrayList<>();

import java.util.*;

12

Our First ArrayList

ArrayList<String> myArrayList = new ArrayList<>();

13

Our First ArrayList

ArrayList<String> myArrayList = new ArrayList<>();

14

Our First ArrayList

ArrayList<String> myArrayList = new ArrayList<>();

Type of items your ArrayList will store.

15

Our First ArrayList

ArrayList<String> myArrayList = new ArrayList<>();

16

Our First ArrayList

ArrayList<String> myArrayList = new ArrayList<>();

17

Our First ArrayList

ArrayList<String> myArrayList = new ArrayList<>();

18

Our First ArrayList// Create an (initially empty) listArrayList<String> list = new ArrayList<>();

19

Our First ArrayList// Create an (initially empty) listArrayList<String> list = new ArrayList<>();

// Add an element to the backlist.add("Hello"); // now size 1

“Hello”

20

Our First ArrayList// Create an (initially empty) listArrayList<String> list = new ArrayList<>();

// Add an element to the backlist.add("Hello"); // now size 1

list.add("there!"); // now size 2

“Hello”

“Hello” “there!”

21

Our First ArrayList// Add an element to the backlist.add("Hello"); // now size 1

list.add("there!"); // now size 2

// Access elements by index (starting at 0!)println(list.get(0)); // prints "Hello"println(list.get(1)); // prints "there!”println(list); // prints ["Hello", "there!"]

“Hello”

“Hello” “there!”

22

Our First ArrayList// Add an element to the backlist.add("Hello"); // now size 1

list.add("there!"); // now size 2

// Access elements by index (starting at 0!)for (int i = 0; i < list.size(); i++) {println(list.get(i));

}

“Hello”

“Hello” “there!”

23

Our First ArrayList// Add an element to the backlist.add("Hello"); // now size 1

list.add("there!"); // now size 2

// Access elements by index (starting at 0!)for (int i = 0; i < list.size(); i++) {println(list.get(i));

}

“Hello”

“Hello” “there!”

24

Our First ArrayList// Add an element to the backlist.add("Hello"); // now size 1

list.add("there!"); // now size 2

// Access elements in order (also for arrays!)for (String str : list) {println(str);

}

“Hello”

“Hello” “there!”

25

Iterating Over ArrayLists// Access elements in order (also for arrays!)for (String str : list) {println(str);

}

// equivalent to

for (int i = 0; i < list.size(); i++) {String str = list.get(i);println(str);

}

26

Iterating Over ArrayLists// Access elements in order (also for arrays!)for (String str : list) {println(str);

}

// equivalent to

for (int i = 0; i < list.size(); i++) {String str = list.get(i);println(str);

}

27

Bad Times with ArrayLists// Create an (initially empty) listArrayList<String> list = new ArrayList<>();

// Wrong type – bad times! Won’t compileGLabel label = new GLabel("Hello there!");list.add(label);

// Invalid index! IndexOutOfBounds Exceptionprintln(list.get(2));

28

Plan for today•Recap:Tic-Tac-Toe•ArrayLists•Example:reversiblewriting•Example:planner•ArrayLists vs.arrays•Recap

29

Example: Reversible Writing

IamnotapersonwhocontributesAndIrefusetobelievethat

Iwillbeuseful

Let’s write a program that reverses a text file.

30

Example: Reversible Writing

IamnotapersonwhocontributesAndIrefusetobelievethat

Iwillbeuseful

IwillbeusefulAndIrefusetobelievethat

Iamnotapersonwhocontributes

Let’s write a program that reverses a text file.

"I Have a Dream" by Antonia Lee, Sara Fung, Christy Fung, Rachel Lamhttp://poets.spice.org.hk/index.php?option=com_content&view=article&id=45:my-family&catid=6:reverse-poem&Itemid=7

31

Example: Reversible WritingLet’s write a program that reverses a text file.

“Iamnotapersonwhocontributes”

32

Example: Reversible WritingLet’s write a program that reverses a text file.

“Iamnotapersonwhocontributes”"AndIrefusetobelievethat"

33

Example: Reversible WritingLet’s write a program that reverses a text file.

“Iamnotapersonwhocontributes”"AndIrefusetobelievethat"

“Iwillbeuseful”

Key idea: fill an ArrayList with each line in the file

34

Example: Reversible WritingLet’s write a program that reverses a text file.

“Iamnotapersonwhocontributes”"AndIrefusetobelievethat"

“Iwillbeuseful”

35

Example: Reversible WritingLet’s write a program that reverses a text file.

“Iamnotapersonwhocontributes”"AndIrefusetobelievethat"

“Iwillbeuseful”

Key idea: print the ArrayList items in reverse order

36

Example: Reversible WritingString filename = promptUserForFile("Filename: ", "res");try {Scanner s = new Scanner(new File(filename));ArrayList<String> lines = new ArrayList<>();

// Read all lines and store in our ArrayListwhile (scanner.hasNextLine()) {

lines.add(scanner.nextLine());}

// Output the lines from back to frontfor (int i = lines.size() - 1; i >= 0; i--) {

println(lines.get(i));}

} catch (IOException ex) {println("Could not read file.");

}

37

Example: Reversible WritingString filename = promptUserForFile("Filename: ", "res");try {Scanner s = new Scanner(new File(filename));ArrayList<String> lines = new ArrayList<>();

// Read all lines and store in our ArrayListwhile (scanner.hasNextLine()) {

lines.add(scanner.nextLine());}

// Output the lines from back to frontfor (int i = lines.size() - 1; i >= 0; i--) {

println(lines.get(i));}

} catch (IOException ex) {println("Could not read file.");

}

38

Example: Reversible WritingString filename = promptUserForFile("Filename: ", "res");try {Scanner s = new Scanner(new File(filename));ArrayList<String> lines = new ArrayList<>();

// Read all lines and store in our ArrayListwhile (scanner.hasNextLine()) {

lines.add(scanner.nextLine());}

// Output the lines from back to frontfor (int i = lines.size() - 1; i >= 0; i--) {

println(lines.get(i));}

} catch (IOException ex) {println("Could not read file.");

}

39

Example: Reversible WritingString filename = promptUserForFile("Filename: ", "res");try {Scanner s = new Scanner(new File(filename));ArrayList<String> lines = new ArrayList<>();

// Read all lines and store in our ArrayListwhile (scanner.hasNextLine()) {

lines.add(scanner.nextLine());}

// Output the lines from back to frontfor (int i = lines.size() - 1; i >= 0; i--) {

println(lines.get(i));}

} catch (IOException ex) {println("Could not read file.");

}

40

Example: Reversible WritingString filename = promptUserForFile("Filename: ", "res");try {Scanner s = new Scanner(new File(filename));ArrayList<String> lines = new ArrayList<>();

// Read all lines and store in our ArrayListwhile (scanner.hasNextLine()) {

lines.add(scanner.nextLine());}

// Output the lines from back to frontfor (int i = lines.size() - 1; i >= 0; i--) {

println(lines.get(i));}

} catch (IOException ex) {println("Could not read file.");

}

41

Example: Reversible WritingString filename = promptUserForFile("Filename: ", "res");try {Scanner s = new Scanner(new File(filename));ArrayList<String> lines = new ArrayList<>();

// Read all lines and store in our ArrayListwhile (scanner.hasNextLine()) {

lines.add(scanner.nextLine());}

// Output the lines from back to frontfor (int i = lines.size() - 1; i >= 0; i--) {

println(lines.get(i));}

} catch (IOException ex) {println("Could not read file.");

}

42

Example: Reversible WritingString filename = promptUserForFile("Filename: ", "res");try {Scanner s = new Scanner(new File(filename));ArrayList<String> lines = new ArrayList<>();

// Read all lines and store in our ArrayListwhile (scanner.hasNextLine()) {

lines.add(scanner.nextLine());}

// Output the lines from back to frontfor (int i = lines.size() - 1; i >= 0; i--) {

println(lines.get(i));}

} catch (IOException ex) {println("Could not read file.");

}

43

Example: Reversible WritingString filename = promptUserForFile("Filename: ", "res");try {Scanner s = new Scanner(new File(filename));ArrayList<String> lines = new ArrayList<>();

// Read all lines and store in our ArrayListwhile (scanner.hasNextLine()) {

lines.add(scanner.nextLine());}

// Output the lines from back to frontfor (int i = lines.size() - 1; i >= 0; i--) {

println(lines.get(i));}

} catch (IOException ex) {println("Could not read file.");

}

44

Plan for today•Recap:Tic-Tac-Toe•ArrayLists•Example:reversiblewriting•Example:planner•ArrayLists vs.arrays•Recap

45

ArrayList Methodslist.add(value); appendsvalueatendoflistlist.add(index, value); insertsgivenvaluejustbeforethegivenindex,

shiftingsubsequentvaluestotherightlist.clear(); removesallelementsofthelistlist.get(index) returnsthevalueatgivenindexlist.indexOf(value) returnsfirstindexwheregivenvalueisfoundinlist

(-1ifnotfound)list.isEmpty() returnstrue ifthelistcontainsnoelementslist.remove(index); removes/returnsvalueatgivenindex,shifting

subsequentvaluestotheleftlist.remove(value); removesthefirstoccurrenceofthevalue,ifanylist.set(index, value); replacesvalueatgivenindexwithgivenvaluelist.size() returnsthenumberofelementsinthelistlist.toString() returnsastringrepresentationofthelist

suchas"[3, 42, -7, 15]"

46

Insert/remove• Ifyouinsert/removeinthefrontormiddleofalist,elementsshift tofit.

list.add(2, 42);• shiftelementsrighttomakeroomforthenewelement

list.remove(1);• shiftelementslefttocoverthespaceleftbytheremovedelement

index 0 1 2 3 4value 3 8 9 7 5

index 0 1 2 3 4 5value 3 8 42 9 7 5

index 0 1 2 3 4 5value 3 8 42 9 7 5

index 0 1 2 3 4value 3 42 9 7 5

47

Example: Planner

48

Example: Planner• Let’swriteaprogramtohelpplanoutourday

– Theprogramfirstpromptsforthingsyouwanttodotoday– Then,itaskstheusertore-inputtheminorderofcompletion– Finally,itoutputstheordertheuserhaschosenfortheirtasks

49

Planner: Approach

“Walk Daisy”

Todos:

50

Planner: Approach

“Walk Daisy”

“Play Zelda”

Todos:

51

Planner: Approach

“Walk Daisy”

“Play Zelda”

“Lunch with Avi”

Todos:

52

Planner: Approach

“Walk Daisy”

“Play Zelda”

“Lunch with Avi”

Todos:

Order: “WalkDaisy”

53

Planner: Approach

“Play Zelda”

“Lunch with Avi”

Todos:

Order: “WalkDaisy”

54

Planner: Approach

“Play Zelda”

Todos:

Order: “WalkDaisy”

“Lunch with Avi”

55

Planner: Approach

Todos:

Order: “WalkDaisy”

“Lunch with Avi”

“Play Zelda”

DONE!

56

Plan for today•Recap:Tic-Tac-Toe•ArrayLists•Example:reversiblewriting•Example:planner•ArrayLists vs.arrays•Recap

57

ArrayLists + Primitives = 💔// Doesn’t compile LArrayList<int> list = new ArrayList<>();

Unlike arrays, ArrayLists can only store objects!

58

ArrayLists + Primitives = 💔

Primitive “Wrapper”Classint Integerdouble Doubleboolean Booleanchar Character

59

ArrayLists + Wrappers = ❤// Use wrapper classes when making an ArrayListArrayList<Integer> list = new ArrayList<>();

// Java converts Integer <-> int automatically!int num = 123;list.add(num);

int first = list.get(0); // 123

Conversion happens automatically!

60

Array vs. ArrayListArrayList

ArrayList<Integer> list = new ArrayList<>();

list.add(1); // [1]list.add(2); // [1, 2]

list.set(0, 3); // [3, 2]int x = list.get(0); // 3

list.add(4); // [3, 2, 4]list.contains(2); // true

Array

int[] arr = new int[2]; // [0, 0]

arr[0] = 1; // [1, 0]arr[1] = 2; // [1, 2]

arr[0] = 3; // [3, 2]int x = arr[0]; // 3

[no equivalent]

61

Array vs. ArrayList

Whydobothoftheseexistinthelanguage?– ArraysareJava'sfundamentaldatastorage– ArrayList isalibrarybuiltontopofanarray

WhenwouldyouchooseanarrayoveranArrayList?– Whenyouneedafixedsizethatyouknowaheadoftime

–Simplersyntaxforgetting/setting–Moreefficient

– Multi-dimensional arrays(e.g.images)– Histograms/tallying

62

Plan for today•Recap:Tic-Tac-Toe•ArrayLists•Example:reversiblewriting•Example:planner•ArrayLists vs.arrays•Recap

63

Recap• ArrayLists areavariabletyperepresentingalistofitems• Unlikearrays,ArrayLists have:

– Theabilitytoresizedynamically– Usefulmethodsyoucancallonthem

• UnlikeArrayLists,arrayshave:– Theabilitytostoreanytypeofitem,notjustobjects

NextTime:HashMaps