{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

02-arraylist - CSE 143 Lecture 2 ArrayList reading 10.1...

Info iconThis preview shows pages 1–8. Sign up to view the full content.

View Full Document Right Arrow Icon
CSE 143 Lecture 2 ArrayList reading: 10.1 slides created by Marty Stepp http://www.cs.washington.edu/143/
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
2 Exercise • Write a program that reads a file and displays the words of that file as a list. First display all words. Then display them with all plurals (ending in "s") capitalized. Then display them in reverse order. Then display them with all plural words removed. • Should we solve this problem using an array? Why or why not?
Background image of page 2
3 Naive solution String[] allWords = new String[ 1000 ]; int wordCount = 0; Scanner input = new Scanner(new File("data.txt")); while (input.hasNext()) { String word = input.next(); allWords[wordCount] = word; wordCount++; } • Problem: You don't know how many words the file will have. Hard to create an array of the appropriate size. Later parts of the problem are more difficult to solve. • Luckily, there are other ways to store data besides in an array.
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
4 Collections collection : an object that stores data; a.k.a. "data structure" the objects stored are called elements some collections maintain an ordering; some allow duplicates typical operations: add , remove , clear , contains (search), size examples found in the Java class libraries: •ArrayList , LinkedList , HashMap , TreeSet , PriorityQueue all collections are in the java.util package import java.util.*;
Background image of page 4
5 Java collection framework
Background image of page 5

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
6 Lists list : a collection storing an ordered sequence of elements each element is accessible by a 0-based index a list has a size (number of elements that have been added) elements can be added to the front, back, or elsewhere in Java, a list can be represented as an ArrayList object
Background image of page 6
7 Idea of a list • Rather than creating an array of boxes, create an object that represents a "list" of items. (initially an empty list.) [] • You can add items to the list.
Background image of page 7

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 8
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}