ARRAYLIST..Hazen High School
Vocabulary to Know• ArrayList• Generic Class• ArrayList Operations• ArrayList Methods• ArrayList Searching• For-Each• Wrapper Class• Boxing • Unboxing
• Comparable• Comparison function• Natural Ordering
What ?
• Resizable Array [Automatic]
• Allows Duplication.
• Order - Maintains Insertion order.
• Type Safety
• Capacity and Size
Array List• The ArrayList class extends AbstractList and implements
the List interface. • ArrayList supports dynamic arrays that can grow as
needed. • In Java, standard arrays are of a fixed length. After arrays
are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold
Array Lists• an ArrayList can dynamically increase or decrease in size. • Array lists are created with an initial size. • When this size is exceeded, the collection is automatically
enlarged. • When objects are removed, the array may be shrunk
Methods and Fields• ArrayList list = new ArrayList()
• Assignment / Insertion• list.Add(“Item1”); // Syntax : list.add(<Object>)
• Size : • int arrayListLength = list.Size();
• Retrieval : • String firstString = list.get(0); // Syntax : list.get(<Index>)
• Removal : • list.Remove(0) // Syntax : list.Remove(<Index>)
• Others• IsEmpty(), Clear(), ToArray(), Set(Index, Object)
• See full reference list at end of the slide deck.
Generics - Type Parameters
ArrayList<Type> name = new ArrayList<Type>();
• When constructing an ArrayList, you must specify the type �of elements it will contain between < and >.
• This is called a type parameter or a generic class.�• Allows the same ArrayList class to store lists of different �
types.
•ArrayList<String> names = new ArrayList<String>();•names.add(“Kory Srock”); names.add(“Tod Oney”);
Generics• Using different classes in Collection.
• Why ?• Better programmability• Better Object Orientation
• Example• ArrayList myList = new ArrayList();• ArrayList<int > a = new ArrayList<int >()• ArrayList<Vehicle> list = new ArrayList<Vehicle >()
Array Vs ArrayList• Grows automatically
• Work well with Generics• ArrayList<String> stringArrayList = new ArrayList<String>();• ArrayList<MyClass> stringArrayList = new ArrayList<MyClass>();
• Objects vs References• Pass by Value --- Pass by Reference
ArrayList of primitives?• The type you specify when creating an ArrayList must be
an object type; it cannot be a 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 special classes called wrapper classes in their place.
// creates a list of ints
ArrayList<Integer> list = new ArrayList<Integer>();
Wrapper classes A wrapper is an object whose sole
purpose is to hold a primitive value.
Once you construct the list, use it with primitives as normal:
Primitive Wrapper
intType IntegerType
double Double
char Character
boolean Boolean
ArrayList<Double> grades = new ArrayList<Double>();grades.add(3.2); grades.add(2.7);... double myGrade = grades.get(0
ArrayList versus Array – Code Examples• Construction
String[] names = new String[5];
ArrayList<String> list = new ArrayList<String>();• Storing a value
names[0] = "Michael";
list.add("Michael");• Retrieving a value
String s = names[0];
String s = list.get(0);
ArrayList vs Array – Code Examples Continued• 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 < list.size(); i++) {
if (list.get(i).startsWith("B")) { ... } }
• Seeing whether the value "Nathaniel" is found for (int i = 0; i < names.length; i++) {
if (names[i].equals("Nathaniel")) { ... }}
if (list.contains("Nathaniel")) { ... }
Objects storing collections• An object can have an array, list, or other collection as a
field.public class Course {
private double[] grades;
private ArrayList<String> studentNames;
public Course() {
grades = new double[4];
studentNames = new ArrayList<String>();
...
}
• Now each object stores a collection of data inside it.• This is called “composition” (the collection is a
component)
Exercise #1• Write a method addStars that accepts an array list of
strings as a parameter and places a * after each element.— Example: if an array list named list initially stores:
[the, quick, brown, fox]
— Then the call of addStars(list); makes it store:
[the, *, quick, *, brown, *, fox, *]
• Write a method removeStars that accepts an array list of strings, assuming that every other element is a *, and removes the stars (undoing what was done by addStars above).
Questions
ArrayList list = new ArrayList()
list.Add(“Item1”);
list.Add(“Item1”);
list.Add(“Item2”);
Will this compile ?
Yes, assuming declaration ofimport java.util.ArrayList;
Questions.. Cntd..
• ArrayList list = new ArrayList()• list.Add(“1”);• list.Add(“2”);• list.Add(3);
Will this compile ?
Yes, all are added as objects
Questions.. Cntd..• ArrayList list = new ArrayList(3)• list.Add(“1”);• list.Add(“2”);• list.Add(“3”);• list.Add(“4”);
Will this compile ?
Yes. ArrayList grows dynamically
Questions.. Cntd..
• ArrayList list = new ArrayList(4)• list.Add(“1”);• list.Add(“2”);• list.Add(“2”);• list.Add(“4”);• System.out.println(list.indexOf(“2”));
Will this compile ?
Output ?
Yes, it will compile
Output is 1
Questions.. Cntd..• ArrayList list = new ArrayList(4);• list.add(“1”);• list.add(“2”);• list.add(“2”);• list.add(“4”);• for(int i=0;i<5;i++)
• System.out.println(list.get(i));
Will this compile ?Output ?
No, IndexOutOfBoundsException
What do we need to do to fix it?
Change for loop to 4 instead of 5
Question .. TrickyArrayList arr1 = new ArrayList();
ArrayList arr2 = arr1;
arr1.Add("Test");
System.out.println(arr1.Length == arr2.Length);
Compile?
Output ?
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
arr1.Add("Test");
arr2.Add(arr1.get(0));
arr1[0] = “Test1”;
System.out.println(arr2.get(0));
Compile?
Output ?
No, there is no method .length for arraylists, need to use .size
What is the output once we change .length to .size?
true
Won’t compile – arr1[0]= “Test1” is a array type conflict
What do we need to do to fix it?
Arr1.add(“Test1”)
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList(); // create an array list
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
What is the initial size of al?
What is the size of al after additions?
What is the contents of al?
What is the size after deletions?
Exercise #2• Use Array List to implement the following exercise• Create and Display a List of Employees in a Company with each Employee
information containing the following• Id• Name• Date of Birth• Designation• Address• Skill Sets [ Accounts, Sales, Marketing, IT, Support, Management, Delivery ]• List of products worked [ ProjectX, PriojectY, ProjectZ, ProjectH ]
• Each Project should track the list of Employees in it• Each Dept./Skill Sets should track the list of Employees in it • Hint :
• Use Static variables to track the List of Employees and Count of them in Project / Department
Array List Methodsadd(value) appends value at end of list
add(index, value) inserts given value just before the given index, shifting subsequent values to the
clear() rightremoves 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
size() valuereturns the number of elements in list
toString() returns a string representation of the list such as "[3, 42, -7, 15]"
Array List Methods ContinuedaddAll(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
contains(value) index)returns true if given value is found somewhere in
containsAll(list) this listreturns true if this list contains every element from
equals(list) given listreturns true if given other list contains the same
iterator() listIterator() elementsreturns 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
remove(value) found)finds and removes the given value from this list
removeAll(list) removes any elements found in the given list from
retainAll(list) this listremoves any elements not found in given list from
subList(from, to) this listreturns the sub-portion of the list between indexes from (inclusive) and to
(exclusive)
toArray() returns the elements in this list as an array
PracticeIt• http://www.garfieldcs.com/2011/02/arraylists-practice/
• http://practiceit.cs.washington.edu/problem.jsp?category=University+of+Washington+CSE+143%2FCS2+Exams%2FCS2+Midterm+Exams%2F143+Practice+Midterm+5&problem=143practicemidterm5-ArrayListMystery
• http://www.garfieldcs.com/2011/03/classes-quiz-practice/
Question .. TrickyArrayList arr1 = new ArrayList();
ArrayList arr2 = arr1.clone();
arr1.Add("Test");
arr2.Add(arr1.get(0));
arr1[0] = “Test1”;
System.Out.PrintLn(arr2.get(0));
Output ?
ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
arr1.Add("Test");
arr2.Add(arr1.get(0).Clone());
arr1[0] = “Test1”;
System.Out.PrintLn(arr2.get(0));
Output ?