Download Announcements ArrayLists: Motivation Collections Lists

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
ArrayLists: Motivation
Announcements
—  “Smart” array!
—  Arrays are fast and useful
—  Today’s topic: ArrayList
—  Reading assignment for this slide set:
—  Section 7.1 (As you read the textbook, don’t worry about implementing
an array list yet. We will do it later. For now, focus on how to use it.)
—  Java Doc page (http://docs.oracle.com/javase/8/docs/api/index.html)
—  Additional: https://www.tutorialspoint.com/java/java_arraylist_class.htm
—  Break around 11:45am
1
Collections
—  But not very convenient
—  Need to know the size to create one and can’t resize it
—  What if you don't know the size up front? E.g.,
—  Data could be 'streaming' in, e.g., Tweeter feed, remote sensors, etc.
—  Would be nice to have an array-like ’thing’ (collection?) that can
—  dynamically resize as needed
—  add an element in the middle and shifting happens automatically
—  fill the 'hole' automatically if an element is removed in the middle
somewhere
—  maintain the elements in the order that they came in
—  etc.
2
Lists
—  List: a collection storing an ordered sequence of elements
—  Each element is accessible by a 0-based index
—  A collection is an object that contains other objects as elements
has a size (in addition to an unknown capacity)
—  Some collections maintain an ordering, some allowing duplicates
—  A list
—  Typical operations: add, remove, contains, clear, size
—  In Java, a list can be represented as an ArrayList object
—  Elements can be added to the front, back, or elsewhere
—  Examples found in Java class libraries (java.util.*):
—  ArrayList, LinkedList, TreeSet, HashSet, TreeMap, HashMap,
PriorityQueue
3
4
1
Idea of a list (‘listness’ property)
ArrayList methods
—  Rather than creating an array, create an object that represents a
“list” of items, initially an empty list, [ ]
—  You can add items to the list
—  The default behavior is to add to the end of the list
[one, hi, two, there, sure, okay, apple ]
—  The list object keeps track of the elements that have been added,
their order, indices, the number of elements (size), etc.
—  Think of an 'array list' as an automatically resizing array object
—  Internally, the list is implemented using a regular array (will implement
one ourselves later)
add(value)
appends value at end of list
add(index, value)
inserts given value just before the given index,
shifting subsequent values to the right
clear()
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 value
size()
returns the number of elements in list
toString()
returns a string representation of the list
such as "[3, 42, -7, 15]"
5
ArrayList methods (cont.)
6
Example - exercise
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 index)
contains(value)
returns true if given value is found somewhere in this list
containsAll(list)
returns true if this list contains every element from given list
equals(list)
returns true if given other list contains the same elements
iterator()
listIterator()
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 found)
remove(value)
finds and removes the given value from this list
removeAll(list)
removes any elements found in the given list from this list
retainAll(list)
removes any elements not found in given list from this list
subList(from, to)
returns the sub-portion of the list between
indexes from (inclusive) and to (exclusive)
toArray()
returns the elements in this list as an array
—  See UseArrayList.java
7
—  Write a spell checker using an ArrayList
—  Read a file of dictionary words into an ArrayList object
—  And provide an interface for a user to spell check words
8
2
Type parameters (Generics)
ArrayList vs. array
ArrayList<Type> a1 = new ArrayList<Type>();
—  Construction
String[] names = new Strings[10];
ArrayList<String> ns = new ArrayList<String>();
—  When constructing an ArrayList, you must specify the type of
elements it will contain as a parameter between < and >
—  This is called a type parameter, used in a generic class
—  Storing a value
—  ArrayList<T> is a parameterized type!
names[0] = “Jennie”;
ns.add(“Jennie”);
—  Allows the same ArrayList class to store lists of different types
ArrayList<String> names = new ArrayList<String>();
names.add(“Amy Jones”);
names.add(“John Smith”);
—  Retrieving a value
String s = names[0];
String s = ns.get(0);
9
ArrayList vs. array (cont.)
10
Exercise
—  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<ns.size(); i++) {
if (ns.get(i).startsWith(“B”)) {...}
}
—  Write a program that reads a file of words and displays the words as
a list
—  First, display all words
—  Then, display them with all plural words (ending in “s”) removed
—  Seeing whether the value “Billy” is found
for (int i = 0; i < names.length; i++) {
if (names[i].equals(“Billy”)) {...}
}
if (ns.contains(“Billy”)) {...}
11
12
3
Solution (partial)
ArrayList as a parameter
ArrayList<String> allWords = new ArrayList<String>();
Scanner input = new Scanner(new File(“words.txt”));
while (input.hasNext()) {
String word = input.next();
allWords.add(word);
}
System.out.println(allWords);
// remove all plural words
for (int i = 0; i < allWords.size(); i++) {
String word = allWords.get(i);
if (word.endsWith(“s”)) {
Is this
allWords.remove(i);
}
}
System.out.println(allWords);
public static void mname (ArrayList<E> par) {...}
public static ArrayList<E> mname (params) {...}
// remove all plural words from the given list
public static void removePlurals(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
String str= list.get(i);
if (str.endsWith(“s”)) {
list.remove(i);
}
}
}
correct?
13
ArrayList of primitives?
14
Wrapper classes
—  A wrapper is an object whose sole purpose is to hold a primitive
value.
—  The type you specify when creating an ArrayList must be an
object type: it cannot be a primitive type.
Primitive Type
// illegal – int cannot be a type parameter
ArrayList<int> list = new ArrayList<int>();
—  But we can still use ArrayList with primitive types by using
Wrapper Type
int
Integer
double
Double
char
Character
boolean
Boolean
special classes called wrapper classes in their place.
—  Once you construct the list, use it with primitives as normal:
// creates a list of ints as Integer’s
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Double> grades = new ArrayList<Double>();
grades.add(3.2); //no need to do grades.add(new Double(3.2));
grades.add(2.7);
...
double myGrade = grades.get(0);
15
16
4
Looping through an ArrayList
Exercise
—  Use an iterator object
—  Write a program that reads a file of numbers and
// students is an ArrayList<Student>
Iterator<Student> itr = students.iterator();
while (itr.hasNext()) {
Student s = itr.next();
// do something with s
}
displays all the numbers as a list, then:
—  Filters out all of the even numbers.
—  Use a for-each loop
for (Student s : students) {
// so something with s
}
17
Solution (partial)
ArrayList<Integer> numbers = new ArrayList<Integer>();
Scanner input = new Scanner(new File("numbers.txt"));
while (input.hasNextInt()) {
int n = input.nextInt();
numbers.add(n);
}
System.out.println(numbers);
removeEvens(numbers);
System.out.println(numbers);
...
// Removes all elements with even values from the given list.
public static void removeEvens(ArrayList<Integer> list) {
for (int i = list.size() - 1; i >= 0; i--) {
int n = list.get(i);
if (n % 2 == 0) {
Is this correct?
list.remove(i);
}
}
19
}
18
Out-of-bounds
—  Legal indexes are between 0 and the list's size() – 1 inclusive.
—  Reading or writing any index outside this range will cause an
IndexOutOfBoundsException
ArrayList<String> names = new ArrayList<String>();
names.add("Mary");
names.add("Kevin");
names.add("Vicki"); names.add("Larry");
System.out.println(names.get(0));
// okay
System.out.println(names.get(3));
// okay
System.out.println(names.get(-1));
// exception
names.add(4, "Aimee");
// okay!
names.add(9, "Aimee");
// exception
index
value
0
1
2
3
Mary Kevin Vicki Larry
20
5
ArrayList "mystery"
ArrayList "mystery” 2
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) {
list.add(10 * i);
// [10, 20, 30, 40, ..., 100]
}
—  What is the output of the following code?
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) {
list.add(2 * i);
// [2, 4, 6, 8, 10]
}
—  What is the output of the following code?
for (int i = 0; i < list.size(); i++) {
list.remove(i);
}
System.out.println(list);
int size = list.size();
for (int i = 0; i < size; i++) {
list.add(i, 23);
// add 23 at index i
}
System.out.println(list);
—  Answer: ???
—  Answer: ???
21
22
Objects storing collections
—  An object can have an array, list, or other collection as a field.
public class Course {
private double[] grades;
private ArrayList<Student> students;
public Course() {
grades = new double[4];
students = new ArrayList<Student>();
...
}
—  Now each Course object stores collections of data inside it.
23
6