Lecture Notes 23: Generics and Data Structures.
Objectives
By the end of this module, you will be able to:
- Understand how to use Generics.
- Utilize the ArrayList Java API.
- Demonstrate understanding of the differences between ArrayList
and Java arrays.
Before Starting
If you do not have your Codio course ready, use any text editor or simple IDE. Some possibilities are:
- Write using Sublime; Compile and run in the Terminal
- Use IDEs like: IntelliJ, DrJava, or JGrasp
ArrayList
Data-structures are means for organizing and accessing data. They
are one of the main topics in CSCI1112.
Examples we've seen so far:
- Two dimensional arrays for organizing spreadsheets, mazes, and
game state.
- FBUsers and Nodes used to keep complex data and connect them to each other.
- Strings for holding collections of characters.
Please take a few minutes to browse
the ArrayList Javadoc
page.
Activity 1 [Group Work]: Questions -
What do you think that this
means: public class ArrayList<E>
What is the "<E>"?
ArrayLists are similar to arrays. How do we find the value at
an index into the ArrayList?
How do we add/change a value at a specific index?
What is the equivalent of array's ".length"?
If we want to get the data in the ArrayList in an
array?
What if we want to do something similar to String's
".substring" method?
Generics
Data-structures contain data. We want the type of the data
to be different, depending on what data we're organizing
- Are we organizing contact information in a list of friends?
- Are we organizing doubles in our spreadsheet?
- Are we organizing Strings in a word processor?
How do we have different arrays containing different types of
data?
FBUser[] friends = new FBUser[n];
double[][] spreadsheet = new double[4][10];
String[] sentences = new String[numSentences];
More complex data-structures must be implemented in Java classes
(often by us!).
However, we don't know how to write a class that can store data of a type that will be later specified by a client, or user of
our class.
Generics enable us to write a class that stores data of a
type specified by the user of our class.
What do generics look like?
public class ArrayList<E>
E is the type of data we want to hold in the ArrayList
Creating an ArrayList that holds Strings:
ArrayList<String> sentences = new ArrayList<String>();
Note: we are specifying that we want to create an array
list of strings
Activity 2 [Group Work]: Write a program that
creates an ArrayList of Strings, put three strings into it, and then
print out the contents of the ArrayList as well as its size.
Activity 3 [Group Work]:
Add code to your program to do the following:
- Find the index of one of the strings.
- Remove an item from the ArrayList and replace it with another
String.
- Add Strings until you have a total of five, and then create an array of Strings that contains the middle three
Strings in the ArrayList.
For each of these, use
no loops and only use the ArrayList
methods.
Other Data-Structures
Check out
the LinkedList Javadoc.
Activity 4 [Group Work]: Questions -
- How do you add values to a linked list?
- How do you find the value at an index?
- Having a little Deja vu? ("It happens when they change something.")
Activity 5 [Group Work]: What is the
difference between arrays, ArrayLists, and LinkedLists? Why does
Java have three implementations of ways of storing data?
An aside aboout class-types for primitives
It turns out that all the familiar oprimitives (int, double, boolean, char, etc) have Class types that define some methods and properties for peerforming high level tasks with them.
- For "int"s, you have a class type of Integer
- For "double"s, you have a class type of Double
- For "boolean"s, you have a class type of Boolean
- For "char"s, you have a class type of Character
We've used these when converting to and from string:
public class CopyExample3 {
public static void main (String[] argv)
{
String s = "123";
int num = Integer.parseInt(s);
System.out.println (num + 4);
}
}
This code willl print a
127 rather than
1234.
When using generics:
If you want to use generics with "primitives", you must use the
Class type instead of the primitive verision.
Activity 6 [Group Work]: Add the
following code to GenericsExample.java. Then, fix the code so that it compiles and runs.
ArrayList<int> al = new ArrayList<int>();
al.add(10);
System.out.println(al.get(0));
Note that there are corresponding types for
- double → Double
- float → Float
- boolean → Boolean
Using these classes, Java automatically converts code such as
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(10);
to
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(Integer(10));
Check out
the HashMap Javadoc.
Activity 7 [Group Work]: Questions -
- What does the <K,V> mean in "Class HashMap<K,V>"?
- The main operations for a HashMap are "get" and "put". What do
you think a HashMap does? What is its main use?
- How is it different from LinkedList and ArrayList?
Activity 8 [Group Work]: Write a program for
the IRS that lets us store people, and later look them up by their
social security number (SSN). Use the person class below. Add
three people objects to a HashMap, using their social security
number as the key. Look them up, and print out their names.
public class Person {
private String name;
private int ssn;
public Person(String n, int ssn) {
name = n;
this.ssn = ssn;
}
public String getName() {
return name;
}
public long getSsn() {
return ssn;
}
}
JavaDoc Treasure Hunt
Activity 9 [Group Work]:
Write a program that
- Creates an HashMap of People.
- Populates it with a number of people (key = ssn, value =
Person object).
- Creates an ArrayList with the same contents as all of the
values in the HashMap.
- ...without using loops. It should work just the same if the
HashMap has 3 People, or 3 million.