Data Types and Exceptions in Java
Jim White
Java Developer
Set
also a kind of Collection
Set
objects are, generally, unordered (therefore have no index)List
s are like a pill box for objects; each object in a specific spot in the boxSet
s are like a sack holding objects; where objects are randomly held in the sackSet
Set
List
Set
HashSet
a popular implementationHashSet
Set
implementation for insert, delete and lookup searchesSet
implementationsnull
HashSet
HashSet<String> set = new HashSet<String>();
HashSet
is found in java.util
packageimport java.util.HashSet
.add()
and .remove()
to add, remove objects.remove()
and then .add()
to replace an object.contains()
to check if object already existsnull
set.add("France");
set.add("Japan");
set.add("Brazil");
set.add("Egypt");
set.add(null); // null is allowed
set.remove("Brazil");
boolean z =
set.contains("France"); // z is true
set.add("Japan"); // Ignored
System.out.println(set);
[null, Japan, Egypt, France]
Queue
data structure processes objects in a first in, first out (FIFO) orderQueue
Queue
implementation ArrayBlockingQueue
is in java.util.concurrent
packagejava.util
packageArrayBlockingQueue
import java.util.concurrent; // At the top of the class
// Create new queue that can store 4 Strings
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(4);
.add(object)
or .offer(object)
to add to the tail.add(object)
throws exception when Queue
is at capacity.offer(object)
ignores the new object when at capacityArrayBlockingQueue<String> queue
= new ArrayBlockingQueue<String>(4);
queue.offer("France");
queue.offer("Japan");
queue.offer("Brazil");
queue.offer("Egypt");
queue.offer("China"); // Ignores China
// Causes IllegalStateException
// queue.add("China");
System.out.println(queue);
[France, Japan, Brazil, Egypt]
.remove()
or .poll()
to remove from the head.remove()
throws an exception when Queue
is empty.poll()
returns null
when Queue
is emptyArrayBlockingQueue<String> queue
= new ArrayBlockingQueue<String>(4);
String x = queue.poll(); // x is null
// Causes NoSuchElementException
// String y = queue.remove();
queue.offer("France");
String next = queue.poll();
System.out.println(next);
France
Data Types and Exceptions in Java