ArrayList Introduction
Download
Report
Transcript ArrayList Introduction
Most of the slides are based on a curriculum
purchased from A+ Computer Science
Arraylist is a class that houses an
array. It is internally implemented
in Java as an array.
An ArrayList can store any type. It
can store a combination of types.
All ArrayLists store the first reference
at index/position/subscript 0.
int[] nums = new int[10];
nums
//Java int array
0
1
2
3
4
5
6
7
8
9
0
0
0
0
0
0
0
0
0
0
An array is a group of items all of the
same type which are accessed through
a single identifier.
ArrayList is a descendant of List (which
extends Collection), but because List and
Collection are interfaces, you cannot
instantiate them.
Collection bad = new Collection(); //illegal
List ray = new ArrayList();
//legal
ArrayList list = new ArrayList(); //legal
ray and list store Object references.
ArrayList list;
list
null
null
nothing
list is a reference to an ArrayList.
new ArrayList();
0x213
[]
ArrayLists are Objects.
ArrayList list = new ArrayList();
list
0x213
0x213
[]
list is a reference to an ArrayList.
Example of an ArrayList without
the type <T> identifier:
OUTPUT
h
List ray = new ArrayList();
ray.add("hello");
c
ray.add(“school");
ray.add("contests");
System.out.println(( (String) ray.get(0)).substring(0,1));
System.out.println(( (String) ray.get(2)). substring(0,1));
casting
(must cast in order to send
messages to the object)
ray stores Object references.
Generic ArrayLists are array lists that take
a type parameter. In other words you
identify the type of all the elements in the
array list.
With Java 5, you can now specify which
type of reference you want to store in
the ArrayList.
ArrayList<String> words;
words = new ArrayList<String>();
ArrayList<Double> decNums;
decNums = new ArrayList<Double>();
With Java 5, you can now specify which
type of reference you want to store in
the ArrayList.
ArrayList<Integer> bigStuff;
bigStuff = new ArrayList<Integer>();
ArrayList<Student> studentList;
studentList = new
ArrayList<Student>();
List<String> ray;
OUTPUT
ray = new ArrayList<String>();
ray.add("hello");
h
ray.add(“school");
c
ray.add("contests");
System.out.println(ray.get(0).substring(0,1));
System.out.println(ray.get(2).substring(0,1));
ray stores String references.
ArrayList
Name
frequently used methods
Use
add(item)
adds item to the end of the list
add(index,item)
adds item at index – shifts items up->
set(index,item)
replaces item at index (returns old element)
get(index)
returns the item at index (similar to z[index] )
size()
returns the number of items in the list (similar
remove(index)
removes the item at index (returns element
that was removed)
remove(value)
removes first item that matches this value
(returns true if item was found, else false)
clear()
removes all items from the list
(similar to z[index]=item)
to z.length)
import java.util.ArrayList;
ArrayList<String> words;
words = new ArrayList<String>();
words.add(0,"it");
OUTPUT
words.add("is");
words.add("a");
[it, is, a, lie]
words.add("lie");
System.out.println(words);
ArrayList<Integer> nums;
nums = new ArrayList<Integer>();
nums.add(34);
OUTPUT
nums.add(0,99);
nums.add(21);
[99, 34, 21, 11]
nums.add(11);
System.out.println(nums);
ArrayList<Integer> ray;
ray = new ArrayList<Integer>();
ray.add(23);
OUTPUT
ray.add(11);
ray.set(0,66);
[66, 93, 53, 22]
ray.add(53);
ray.set(1,93);
ray.add(22);
System.out.println(ray);
for (int i=0; i<ray.size(); i++)
{
System.out.println(ray.get(i));
}
size( ) returns the number of
elements (logical/physical size) in
the array list.
ArrayList<Double> ray;
ray = new ArrayList<Double>();
ray.add(23.23);
ray.add(11.11);
ray.add(12.1);
ray.add(65.6);
OUTPUT
23.23
65.6
System.out.println(ray.get(0));
System.out.println(ray.get(3));
get(index) returns the reference stored
at the index!
ArrayList<Integer> ray;
ray = new ArrayList<Integer>();
ray.add(23);
OUTPUT
ray.add(11);
23
ray.add(12);
11
ray.add(65);
for(int i=0; i<ray.size(); i++)
System.out.println(ray.get(i));
12
65
get(index) returns the reference stored
at the index!
ArrayList<String> ray;
ray = new ArrayList<String>();
ray.add("a");
ray.add("b");
ray.remove(0);
ray.add("c");
ray.add("d");
ray.remove(0);
System.out.println(ray);
OUTPUT
[c, d]
ArrayList<String> ray;
ray = new ArrayList<String>();
ray.add("a");
ray.add("b");
ray.remove("a");
ray.add("c");
ray.add("d");
ray.remove("d");
System.out.println(ray);
OUTPUT
[b, c]
ArrayList<Integer> ray;
ray = new ArrayList<Integer>();
ray.add(5);
OUTPUT
ray.add(4);
[5,
4,
2]
3]
ray.add(3);
ray.add(2);
ray.remove(new Integer(2));
ray.remove(2);
System.out.println(ray);
However, if this line was coded like this
ArrayList<String> ray;
ray = new ArrayList<String>();
ray.add("a");
ray.add("x");
ray.clear();
ray.add("t");
ray.add("w");
System.out.println(ray);
OUTPUT
[t, w]
ArrayList
Name
frequently used methods
Use
add(item)
adds item to the end of the list
add(index,item)
adds item at index – shifts items up->
set(index,item)
replaces item at index (returns old element)
get(index)
returns the item at index (similar to z[index] )
size()
returns the number of items in the list (similar
remove(index)
removes the item at index (returns element
that was removed)
remove(value)
removes first item that matches this value
(returns true if item was found, else false)
clear()
removes all items from the list
(similar to z[index]=item)
to z.length)
import java.util.ArrayList;
ArrayList<Integer> ray =
new ArrayList<Integer>();
ray.add(3);
ray.add(5);
ray.add(12);
ray.add(7);
OUTPUT
[5, 12]
for (int i=0; i<ray.size(); i++)
{
if (ray.get(i) < 10)
{ ray.remove(i); i--; } // fixes bug
}
System.out.println(ray);
ArrayList<Integer> ray;
ray = new ArrayList<Integer>();
ray.add(23);
ray.add(11);
ray.add(53);
for(int num : ray)
{
System.out.println(num);
}
OUTPUT
23
11
53
How can you initialize an ArrayList?
ArrayList<String> names = new ArrayList<String>();
names.add(“Smith”);
names.add(“Jones”);
Or similar to an initializer list for an array:
ArrayList<String> names = new ArrayList<String>
(Arrays.asList("Smith", "Jones"));
import java.util.ArrayList;
import java.util.Arrays;
• Purpose: To get familiar with ArrayLists
• Make a copy of your EmployeeNames and
EmployeeNamesTester classes and name
them EmployeeArrayList and
EmployeeArrayListTester.
• Alternatively, make a copy of Cities and
CitiesTester classes and name them
CitiesArrayList and CitiesArrayListTester.
• In either case, change all occurrences of
arrays to ArrayLists.
Primitive types
Objects
(wrapper class)
byte
Byte
short
int
Short
Integer
long
float
double
char
Long
Float
Double
Character
boolean
==
Boolean
.equals()
Before Java 5 added in autoboxing
and autounboxing, you had to
manually wrap primitives.
Integer x = new Integer(98);
or
int y = 56;
x= new Integer(y);
Java now wraps automatically.
Integer num1 = 99;
and
Integer num1 = new Integer(99);
These two lines are equivalent.
Java now wraps automatically.
Double num1 = 99.1;
and
Double num1 = new Double(99.1);
These two lines are equivalent.
Before Java 5 added in autoboxing
and autounboxing, you had to
manually unwrap references.
If you boxed 98 as an Integer like this:
Integer ref = new Integer(98);
Then you had to unbox it like this:
int y = ref.intValue();
Java now unwraps automatically.
int prim;
Integer num = new Integer(3);
OLD WAY:
prim=num.intValue();
System.out.println(prim);
NEW WAY:
prim = num;
System.out.println(prim);
These two lines are equivalent.
OUTPUT
3
3
OUTPUT
Double dub = 9.3;
double prim = dub;
9.3
System.out.println(prim); 0
-1
int num = 12;
1
Integer big = num;
System.out.println(big.compareTo(12));
System.out.println(big.compareTo(17));
System.out.println(big.compareTo(10));
ArrayList<Integer> ray;
ray = new ArrayList<Integer>();
OUTPUT
153
//add some values to ray
int total = 0;
for(Integer num : ray)
{
//this line shows the manual retrieval of the primitive
total = total + num.intValue(); // total += num.intValue();
//the line below accomplishes the same as the line above
//but it uses autounboxing to get the primitive value
total = total + num;
// total += num;
}
System.out.println(total);
Create a method to return the total
of all the values in an ArrayList.
Here is the method’s signature line:
int total = 0;
public int totalValues(ArrayList<Integer> scores)
{
}
public class Creature implements Comparable
{
private int weight;
Instance variable
public Creature(int wt)
{
weight=wt;
}
Constructor initializes
weight of Creature
public void setWeight(int wt)
{
weight=wt;
}
toString() returns the String
public String toString()
representation of Creature
{
return “Creature which weighs ” + weight + “ lbs”;
}
}
//Other methods not shown here
ArrayList<Creature> creatureList;
creatureList = new ArrayList<Creature>();
creatureList.add(new Creature(4));
creatureList.add(new Creature(9));
creatureList.add(new Creature(1));
creatureList
0
1
2
0x12
0x32
0xD2
Creature
4
Creature
9
Creature
1
ArrayList<Creature> creatureList;
creatureList = new ArrayList<Creature>();
creatureList.add(new Creature(4));
creatureList.add(new Creature(9));
creatureList.add(new Creature(1));
System.out.println(creatureList.get(0));
creatureList.get(0).setWeight(7);
System.out.println(creatureList.get(0));
System.out.println(creatureList.get(2));
OUTPUT
Creature which weighs 4 lbs
Creature which weighs 7 lbs
Creature which weighs 1 lbs
creatureList.get(0). setWeight(7);
0x242
0x242
What
does this
return?
What
does the
. dot do?
Creature
The . dot grants access to the
Object at the stored address.
Ends with an s
Collections
frequently used methods
Name
Use
sort(x)
Puts all items in array list x in ascending order
binarySearch(x,y)
Prerequisite: array list x must be sorted.
Checks x for the location of y. This method
returns the index where y is found. If y is not
found, it returns -1 minus (the position in the
array list where x would be added).
fill(x,y)
Fills all elements in x with value y
rotate(x,y)
Shifts items in x right y positions (if y is
positive) or left y positions (if y is negative)
reverse(x)
Reverses the order of the items in x
import java.util.Collections;
ArrayList<Integer> ray;
ray = new ArrayList<Integer>();
ray.add(23);
ray.add(11);
ray.add(66);
ray.add(53);
Collections.sort(ray);
OUTPUT
[11, 23, 53, 66]
-5
3
System.out.println(ray);
System.out.println(Collections.binarySearch(ray,677));
System.out.println(Collections.binarySearch(ray,66));
ArrayList<Integer> ray = ArrayList<Integer>();
ray.add(23);
ray.add(11);
ray.add(53);
ray.add(100);
System.out.println(ray);
Collections.rotate(ray,1);
System.out.println(ray);
OUTPUT
[23, 11, 53, 100]
[100, 23, 11, 53]
[23, 100, 53, 11]
Collections.rotate(ray,-2); // [11, 53, 100, 23]
Collections.reverse(ray);
System.out.println(ray);
ArrayList<Integer> ray;
ray = new ArrayList<Integer>();
ray.add(0);
ray.add(20);
OUTPUT
ray.add(50);
[0, 20, 50]
System.out.println(ray);
[33, 33, 33]
Collections.fill(ray,33);
System.out.println(ray);
ArrayList
frequently used methods
Name
Use
contains(y)
Checks to see if the list contains y.
Returns either true or false.
indexOf(y)
Checks the array list for the location of
y. Returns the index where y is found.
If not found, it returns -1.
isEmpty()
Returns true if the array list is empty
(no elements) or false if it contains
elements.
ArrayList<Integer> ray;
ray = new ArrayList<Integer>();
ray.add(23);
ray.add(11);
ray.add(66);
ray.add(53);
System.out.println(ray);
System.out.println(ray.indexOf(21));
System.out.println(ray.indexOf(66));
System.out.println(ray);
System.out.println(ray.contains(21));
System.out.println(ray.contains(66));
OUTPUT
[23, 11, 66, 53]
-1
2
[23, 11, 66, 53]
false
true
The following are important
interfaces included in the
Java language:
Collection
List
Map
Collection
Implementing
Classes
Sub
Interfaces
-extends
List
Set
Implementing
Classes
Sub
Interfaces
-extends
SortedMap
HashMap
HashTable
Sub
Interfaces
-extends
SortedSet
Implementing
Classes
ArrayList
LinkedList
TreeSet
Vector
Stack AbstractSet
HashSet
LinkedHashSet
Implementing
Classes
TreeMap
The Collection interface is the parent of List
and Set. The Collection interface has many
methods including add(), clear(), remove(),
and size().
Collection
List
Set
others not shown
The List interface extends the Collection interface.
Additionally, the List interface also has the get()
method as well as several other methods.
List
ArrayList
LinkedList
others not shown
ArrayList is a descendant of List and Collection, but
because List and Collection are interfaces, you cannot
instantiate them.
Collection bad = new Collection();
List justAsBad = new List();
//illegal
//illegal
List list = new ArrayList<Integer>();
//legal
ArrayList aList = new ArrayList<Integer>(); //legal
Collection col = new ArrayList<Integer>(); //legal **
** Legal only if using methods from Collection interface
list, aList, and col store Object references.