JAVA Assignment
INFSCI 2500 Lecture 2 Java Collections Framework
Today’s Goals
Pretest
Intro to Java Review
Understand Collections
Create Parameterized Collections
Understand methods of Collections interface
Understand iterators
Understand lists, sets, and maps
Build our own Collection class
Review
For a file named myFile.java
public class myFile{
public static void main (String[] args){
//Code
}//End main
}//End myFile class
Primitives
BYTE (tiny)
SHORT (small)
INT (regular)
LONG (big)
FLOAT (reals)
DOUBLE (reals, standard)
BOOLEAN (true/false)
CHAR (one letter)
Pointers
PRIMITIVES
int i=1;
Where i points in memory is the value 1.
OBJECTS (reference variables/instances of a class)
String s=new String(“hello”);
Where s points in memory is an address for the object.
Printing an object calls the Object.toString() inherited method, which give the address, unless it is overridden!
Address Example
SomeObject.java
Variable Scope
Local variables – created within a method
Global variables – created for a whole class
public class Dog{
public String name=new String();
public byte age;
public String howOldAreYou(){
String result;
if(age<=2){
result=“bark bark bark”;
}
else{
result=“baroooo”;
}
return result;
}
}
Variable Equality
Primitives
If values are ‘exactly’ the same
Objects
If names are pointing to the same address
In practice, we care about comparing values!
For custom classes, you must write your own equals() method.
Variable Equality Example
SomeObject2.java
Inheritance
Defining a new class that contains fields and methods of another class
public class Pet{
int age;
String name;
} //superclass
public class Dog extends Pet{
String AKCBreed;
} //subclass
Dog IS-A Pet
Pet HAS-A name, age
Dog HAS-A name, age, AKCBreed
Collections
Built-in functionality feature of Java
Collection
Object composed of elements (primitives or objects)
What to do?
Add
Remove
Clear
check the size
check if it is empty
check if it contains a target value
Arrays
Array (contiguous storage)
String[] names = new String[5];
Benefits: random access
Drawbacks: Fixed size, no support for insert or delete
Arrays Example
Searching for an element
Retrieving an element
Deleting an element
Inserting an element
Arrays.java
Collection Class
Each instance is a collection of elements
Elements are objects
Not primitives, wrapper classes
Implement common methods
int i= 3;
Integer myWrappedInt = new Integer(i);
i=myWrappedInt.intValue();
Collections Classes
ArrayList
LinkedList
TreeMap
TreeSet
HashMap
HashSet
Storage Structures
Memory usage is proportional to size
How are references stored in memory?
contiguous-collection (behind the scenes array)
ArrayList, Heap
allows constant-time random access
Drawbacks for users?
Storage Structures
Instead of an array, use links/references (linked-collection)
Linked List, Binary Search Tree, Tree Maps, Hashes
Elements are stored in node objects
Each node has a link to another object and a value
Linked-Collections
Java Collections Framework
Thoroughly tested
Widely used
No “reinventing the wheel”
Many methods in common between classes
Abstract classes and interfaces
Interfaces
Collection of abstract methods and/or constants
No defined methods
Classes implementing the interfaces provide method definitions
public interface Employee{
boolean makesMoreThan(Employee e);
int Salary();
String name();
String status();
}
Interfaces Example
interfaces.java
Abstract Classes
Allowed to have abstract methods and defined methods
Classes extending the abstract class provides method definitions
public abstract class Parent{
public String getPrefix(){
return “I am ”;
}
public abstract String getClassName();
}
Abstract classes cannot be instantiated.
Parent p = new Parent(); //illegal
Abstract Classes
public class Child1 extends Parent{
public String getClassName(){
return “Child1”;
}
}
public class Child2 extends Parent{
public String getClassName(){
return “Child2”;
}
}
//inside the main method
Parent p1=new Child1();
Parent p2=new Child2();
System.out.println(p1.getPrefix() + p1.getClassName());
System.out.println(p2.getPrefix() + p2.getClassName());
What is the output?
Parameterized Types
Declare what kind of objects the collection holds
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(new Integer(15));
Integer k = myList.get(0);
int i = k.intValue();
myList.add(new String “hello”); //illegal
myList.add(16); //boxing
int i = myList.get(1); //unboxing
LinkedList<myCustomClass> list = new LinkedList<myCustomClass>();
Collection Interface
Top of the hierarchy in JCF
Collection Interface
Implemented by most collection classes
Extended by other interfaces
Generic typed
public class LinkedList<E> implements Collection<E>…
LinkedList<Double> myList = new LinkedList<Double>();
Iterators
Accessing each element in a collection is useful
Iterators allow elements of Collections to be accessed
upholds the Principle of Data Abstraction
Iterator Interface
boolean hasNext();
E next();
void remove();
Iterator<E> iterator(); //call this from collection object
ArrayList<String> myList = new ArrayList<String>();
//add some elements to the collection
Iterator<String> itr = myList.iterator();
Iterator Example
String word;
while (itr.hasNext()){
word=itr.next();
if(word.charAt(0)==‘a’){
System.out.println(word);
}
}
Enhanced-For
for(String word: myList){
if(word.charAt(0)==‘a’){
System.out.println(word);
}
}
No need to create the iterator explicitly
Can only access elements, not delete them!
“:” means “in”
for each word in myList,
if the first character equals a
print the word
Deleting Elements
Iterator<String> itr = myList.iterator();
while(itr.hasNext()){
if(itr.next().charAt(0)==‘a’){
itr.remove();
}
}
List Interface
Extends Collection interface for index-related methods
“dog”,”cat”,”bird”
0 1 2
get(index i)
remove(index i)
get(1) -> “cat”
remove(2) -> “dog”,cat”
Implemented by AbstractList class and ArrayList,LinkedList
Each class implements the methods from the interface to work with the behind-the-scenes data structure
Set Interface
Extends Collection interface by prohibiting duplicate objects
Implemented by AbstractSet class and TreeSet, HashSet classes
Set<Integer> mySet = new TreeSet<Integer>();
mySet.add(1);
mySet.add(1); //wont work, no duplicates!
Map Interface
A map is a collection of key-value pairs
Array with string indexes instead of integers
Keys are unique
Email-Name
abc@efg.com – Joe
dws@fg.com – Tom
oig@tgbrt.com - Jack
Map Interface
Does not extend Collection Interface
Implemented by AbstractMap, TreeMap, HashMap Classes
No iterators for Maps
iterate over keys, values, or K-V pairs
Methods are designed for K-V pairs
public V put(K key, V value)
public V remove(K key) //both return value associated with K
Review Questions
What is a collection?
What is a collection class?
What is a Collection class?
Contiguous collection?
Linked collection?
Review Questions
LinkedList<String> x = new LinkedList<String>();
x.add(“hello”);
Iterator<String> itr = team.iterator();
Integer z = itr.next();
Create a collection Class
contiguous-collection
Sequence(int n)
int size()
void append(E element)
E get(int k)
Sequence.java