arraylists 1 - ahs-dib.info · arraylists 1 1/26/17 . objective • understand difference between...
TRANSCRIPT
ArrayLists 1
1/26/17
Objective
• Understand difference between Arrays and ArrayLists
• Using Array Lists
11-2
Arrays – Objects or Not?
• Why the ambiguity about whether arrays are objects?
– Because for an object, they are pretty lame.
– All they bring to the table is that they are passed by reference and they have one field (length).
– True objects would have plenty of methods to use that would make the clients job much easier.
11-3
So what is an ArrayList?
• An ArrayList is a class that handles all of the common operations done with arrays.
– Its field are:
• Object[] arr
• int capacity
• int size
- It’s methods include:
- Constructors (2), remove(), add(), set(), get(), remove(), indexOf(), size(), contains(), toString()
Array of Strings – removing elements
String[] myStringArray = new String[10];
myStringArray[0] = “hi”;
myStringArray[1] = “bye”;
myStringArray[2] = “hola”;
myStringArray[3]= “adios”;
int size = 4;
System.out.println(myStringArray[2]); //hola
myStringArray[1]=myStringArray[2];
//for loop to find index of “hola”
//to delete index, for loop to move items to the right ove
//keep track of size.
“hi” “bye” “hola” “adios”
ArrayList of Strings – removing elements, much easier for client
Appears the same but easier to manage; ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList.add(“hi”);
myArrayList.add(“bye”);
myArrayList.add(“hola”);
myArrayList.add(“adios”);
System.out.println(myArrayList.get(2)); //hola
int index = myArrayList.indexOf(“hola”);
myArrayList.remove(1); //removes “bye”, shifts hola and
//adios over, decreases size
“hi” “bye” “hola” “adios”
Calling the ArrayList constructor
//constructs an empty ArrayList of strings, default
//capacity is 10
ArrayList<String> myList = new ArrayList<String>();
//constructs an ArrayList of Integers with a capacity of
//50.
ArrayList<Integer>myIntList = new ArrayList<Integer>(50);
*The ArrayList constructor is overloaded. If no arguments passed in, a list with a default capacity of 10 is created.
*If you know your size from the beginning, you should use the second constructor, so time is not wasted resizing later.
11-7
Why use an ArrayList instead of an array?
• Common methods available
• We don’t have to keep track of size, we just call size() method.
• Array will automatically increase in size as needed when adding objects.
• When removing objects, array will decrease and move items over as needed.
• Print name of list, and entire contents is printed
11-8
Why use an Array instead of ArrayList?
• Can use primitive data with arrays
• Can initialize in one line
• Can update values in one line
• Takes up less space (memory), generally more efficient
11-10
java.util.ArrayList<E>
• Implements a list using an array
• Implements java.util.List<E> interface
• So sometimes you will see List x = new ArrayList<String>
«interface»
java.util.List
java.util.ArrayList java.util.LinkedList
11-11
java.util.ArrayList<E> cont’d
• Can only hold objects (of a specified type), not elements of primitive data types.(Why is this?)
• Keeps track of the list capacity (the length of the allocated array) and list size (the number of elements currently in the list)
"Cat" "Hat" "Bat"
capacity
size
...
11-12
ArrayList<E> Constructors
ArrayList<E> ( )
ArrayList<E> (int capacity)
Creates an empty
ArrayList<E> of
default capacity (ten)
Java docs use the letter E as
the type parameter for elements
in generic collections
Creates an empty
ArrayList<E> of the
specified capacity
11-13
ArrayList<E> Methods (a Subset)
int size()
boolean isEmpty ()
boolean add (E obj)
void add (int i, E obj)
E set(int i, E obj)
E get(int i)
E remove(int i)
boolean contains(E obj)
int indexOf(E obj) both use E’s
equals to compare
objects
i must be from 0 to size() -1**(not
capacity)
inserts obj as the
i-th value; i must
be from 0 to size()
returns true
11-14
ArrayList Example
ArrayList<String> names =
new ArrayList<String>( );
names.add("Ben");
names.add("Cat");
names.add(0, "Amy");
System.out.println(names);
[Amy, Ben, Cat]
Output ArrayList’s toString
method returns a string of
all the elements, separated
by commas, within [ ].
11-15
ArrayList<E> - Some things to know
• Automatically increases (doubles) the capacity when the list runs out of space (allocates a bigger array and copies all the values into it).
• get(i) and set(i, obj) are efficient because an array provides random access to its elements.
• Throws IndexOutOfBoundsException when
i < 0 or i size()
(or i > size() in add (i, obj) )
11-16
ArrayList<E> Autoboxing
• If you need to put ints or doubles into a list, use a standard Java array or convert them into Integer or Double objects
• Since Java 5, conversion from int to Integer and from double to Double is, in most cases, automatic (a feature known as autoboxing or autowrapping); the reverse conversion (called autounboxing) is also automatic.
11-17
ArrayList<E> Autoboxing Example
ArrayList<Integer> counts =
new ArrayList<Integer>( );
counts.add(17);
...
int count = counts.get(0);
Autoboxing: compiled as
counts.add(new Integer(17));
Autounboxing: count
gets the value 17
11-18
Look at ArrayListDemo.java
• What will print?
Homework 1-4
1. True or False: a. An ArrayList can contain multiple references to
the same object b. The same object may belong to two different
ArrayLists c. ArrayList’s remove method destroys the object
after it has been removed from the list. d. ArrayList’s add method makes a copy of the
object and adds it to the list. e. Two variables can refer to the same ArrayList
Homework #2 T/F
The ArrayList class has a method trimToSize() which trims the capacity of the list to its current size. T/F, calling this method:
a. Saves space in the program
b. Will make add(x) calls more efficient
c. Will make add(0, x) calls more efficient
d. Will make get(i) and set(i, x) more efficient.
HW #3
Why might you use a simple Java array as opposed to an ArrayList?
HW #4
What is the output: ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(0);
myList.add(1);
myList.add(2);
myList.add(0,0);
myList.add(1,1);
myList.add(2,2);
System.out.println(myList);
11-23
Lab: Shuffler • The Shuffler program shuffles the lines of
text, then allows the user to restore the right order.
11-24
Lab: Shuffler (cont’d) • Your job is to write the LineList class, with
one field, ArrayList<String>, and the following methods: – int size () — returns the number of lines
– String get (int k) — returns the line at index k
– void add (String line) — appends line to list
– String remove (int k) — removes and returns the k-th line
– void move(int index, int newIndex) — moves the line at index to the position at newIndex
– void shuffle() — shuffles the lines of text
11-25
Lab: Shuffler (cont’d)
• Use the following algorithm for shuffle:
1. Set n to the size of the list;
2. Randomly select an element among the first n
and swap it with the n-th element;
3. Decrement n by one;
4. Repeat Steps 2-3 while n 2.
Homework
• #5, 6, 7, 8, 9
• Finish lab
• Read 11.5