Java Array Lists

Java Array Lists
2/2/2016
Goals
• A little Object review
• Understand how to create and use an
ArrayList
• Become familiar with the AP Java subset
of ArrayList methods
• Be able to write a program using an
ArrayList.
SL4 (A2.10). Consider the following partial class declaration.
public class Student
{
private String myName;
private double myGPA;
public String name()
{ return myName; }
public double GPA()
{ return myGPA; }
}
Consider the following method from a client class.
public void showInfo(Student stu)
{
System.out.println( /* string expression */ );
}
Which of the following are valid replacements for /* string expression */?
I.
stu.myName + stu.myGPA;
II. Student.name() + Student.GPA();
III. stu.name() + stu.GPA();
Dry Run: Class, instance variables,
constructors, methods, objects, screen
class Number
class NumberTest
{
{
public int value;
public static void main(String[] args)
public Number() { value = 0; }
{
public Number(int val)
Number a = new Number(5);
{ value = val % 100; }
Number b = new Number(1015);
public Number add(Number x)
System.out.println("A = " + a.value);
{
System.out.println("B = " + b.value);
Number result;
Number c = a.add(b);
result = new Number(value + x.value);
Number d = a.sub(b);
return result;
System.out.println("A+B = " + c.value);
}
System.out.println("A-B = " + d.value);
public Number sub(Number x)
}
{
}
Number result;
result = new Number(value - x.value);
return result;
}
}
Review
• Write the code from the Final
• Person class
– Name, yearOfBirth
– Constructors (Default and with values), toString, methods
accessName() and accessYear()
• CollegeStudent class
–
–
–
–
Degree
Constructors (Default and with values)
toString()
accessDegree()
• Teacher class
–
–
–
–
salary
Constructors (Default and with values)
toString()
accessSalary()
Inheritance Review
Time to get classy!!
Write classes for the
following UML Diagrams
Rectangle
- width: int
- height: int
+<<constructor>> Rectangle(color, width, height)
+calculateArea():int
+getWidth(): int
+getHeight(): int
+ toString():String
Shape
- Color: String
+<<constructor>> Shape(color)
+getColor(): String
+toString():String
Circle
- radius: int
+<<constructor>> Circle(color,
radius)
+calculateArea():double
+ getRadius(): int
+ toString(): String
Starting
the
Driver
What do you think the following code will do?
Scanner input = new Scanner(System.in);
ArrayList <String> names = new ArrayList<String>();
String name;
System.out.println("Enter a name");
name = input.next();
while (!name.equals("-1"))
{
names.add(name);
System.out.println("Enter a name");
name = input.next();
}
for(int count = 0; count<names.size();count++)
System.out.println(names.get(count));
Array List
• A dynamic array of objects
• Like a linked list. You can dynamically add to it,
remove from it,…
• You can also have random(ish) access.
• You can add, get, set, and remove an object
using methods (You don’t have to write the code
for these!)
• There are many other methods tied to
ArrayLists!!!! (But we will focus on those in the
AP subset)
Objects only.
• A disadvantage of a ArrayList is that it
holds only objects and not primitive types
(i.e. int).
• To use a primitive type in an ArrayList, put
it inside an object (i.e. to save an integer
value use the Integer ‘wrapper’ class or
define your own class).
Automatic expansion.
• Use ArrayList when there will be a large
variation in the amount of data that you would
put into an array.
• Arrays should be used only when there is a
constant amount of data.
• For example, storing information about the days
of the week should use an array because the
number of days in a week is constant.
• Use an array list for your email contact list
because there is no upper bound on the number
of contacts.
Creating a ArrayList
ArrayList<SomeClass> listName = new ArrayList<SomeClass>();
ArrayList<String> list = new ArrayList<String>();
ArrayList<Integer> num = new ArrayList<Integer>();
AP Subset ArrayList Methods
• x=alist.size(); Returns the number of elements in the
ArrayList.
• alist.add(obj); Adds an object onto the end of the ArrayList,
increasing the size by 1.
• alist.add(index, obj);
– Inserts obj at position index (0<= index < size) moving elements at
position index and higher to the right. Also adjusts the alist’s size.
• objAns = alist.get(index); This returns the element at the
index position.
• objAns = alist.set(index, obj); Assigns the object, obj, to
position N in the ArrayList, replacing the item previously
stored in position N. It also returns the element at index.
• objAns = alist.remove(N); For an integer, N, this removes
the N-th item in the ArrayList. N must be in the range 0 to
alist.size()-1. Any items in the list that come after the
removed item are moved down one position.
Dry Run Problem
CTA18 Consider the following instance variable and method from some
class.
private ArrayList<Integer> values;
public void changeList(int limit)
{
for(int k = 0; k < values.size(); k++)
{
if(values.get(k).intValue() < limit)
values.add(values.remove(k));
}
}
.intValue() returns the int
value of an Integer object.
ArrayList vs. array usage
• import java.util.*;
• construction
– String[] names = new String[5];
– ArrayList <String> namesList = new ArrayList() <String> ;
• storing an element
– names[0] = "Jennifer";
– namesList.add("Jennifer");
– namesList.add(0, "Jennifer");
// or,
• retrieval of an element's value
– String name = names[0];
– String name = namesList.get(0);
ArrayList vs. array, cont'd.
• removal of an element (at index 2)
– for (int i = 2; i < names.length - 1; i++)
names[i] = names[i+1];//Array
– namesList.remove(2);//ArrayList
Review
ArrayList<SomeClass> listName = new ArrayList<SomeClass>();
ArrayList<String> list = new ArrayList<String>();
ArrayList<Integer> num = new ArrayList<Integer>();
x=alist.size();
alist.add(obj);
alist.add(index, obj);
objAns = alist.get(index);
objAns = alist.set(index, obj);
alist.set(index, obj);
objAns = alist.remove(N);
alist.remove(N);
Warm up
• Look up Java Docs to find out what the
following Integer methods do…
• Constructors
• .intValue()
• .compareTo()
• .equals()
Sample Question
• 2. Consider the following code segment.
–
–
–
–
–
–
–
–
ArrayList <Integer> list = new ArrayList<Integer> ();
list.add(new Integer(1));
Note: This will display the entire
list.add(new Integer(2));
arraylist!!
list.add(new Integer(3));
list.set(2, new Integer(4));
list.add(2, new Integer(5));
list.add(new Integer(6));
System.out.println(list);
• What is printed as a result of executing the code segment?
–
–
–
–
–
(A) [1, 2, 3, 4, 5]
(B) [1, 2, 4, 5, 6]
(C) [1, 2, 5, 4, 6]
(D) [1, 5, 2, 4, 6]
(E) [1, 5, 4, 3, 6]
• 3. Consider the following data field and method.
– private ArrayList nums;
– // precondition: nums.size() > 0;
– // nums contains Integer objects
– public void numQuest()
– {
• int k = 0;
• Integer zero = new Integer(0);
• while (k< nums.size())
• {
– if (nums.get(k).equals(zero))
– nums.remove(k);
– k++;
• }
– }
•
•
•
Assume that ArrayList nums initially contains the following Integer values.
[0, 0, 4, 2, 5, 0, 3, 0]
What will ArrayList nums contain as a result of executing numQuest ?
– (A) [0, 0, 4, 2, 5, 0, 3, 0]
– (B) [4, 2, 5, 3]
– (C) [0, 0, 0, 0, 4, 2, 5, 3]
– (D) [3, 5, 2, 4, 0, 0, 0, 0]
– (E) [0, 4, 2, 5, 3]
ArrayList Program #1
• Input and unknown number of names into
an ArrayList
– Show the names in reverse order
• Within 3
– Input an unknown number of integers.
– Output: The total, average and number of
scores within 3 of the average.
• Mini zoo
– Use an ArrayList to make a mini-zoo using the
Animals created previuosly. (Cow, Snake,…
– Be able to add to and show from this zoo.