java course 4: exceptions & collections
DESCRIPTION
Lecture 4 from the IAG0040 Java course in TTÜ. See the accompanying source code written during the lectures: https://github.com/angryziber/java-courseTRANSCRIPT
Exceptions,Exceptions,CollectionsCollections
Java course - IAG0040Java course - IAG0040
Anton Keks 2011
Lecture 4Lecture 4Slide Slide 22
Java course – IAG0040Anton Keks
java.lang.Objectjava.lang.Object
● All objects in Java extend java.lang.Object
● It provides the following methods:
– toString() - returns a String representation of an object, by default it returns getClass().getName() + “@” + hashCode();
– equals(Object o) – checks for equality with another Object, by default just compares references: return this == o;
– hashCode() - returns a (possibly) unique and uniformly distributed int value for the object internal state. Used in hash tables.
– getClass() - returns the Class object, representing its runtime class.
– wait() and notify() - used for synchronization of threads
– clone() - can be overridden to allow cloning (copying) of objects
● equals, hashCode, toString, and clone are overridden quite often
Lecture 4Lecture 4Slide Slide 33
Java course – IAG0040Anton Keks
ExceptionsExceptions● Exceptions exist to separate real code from error checking
● Exceptions are special classes, instances of which can be thrown:
– throw new Exception(“Hello!”);
● Thrown exceptions can be caught:
– try { } catch (Exception e) { } finally { }
● Hierarchy:
Throwable(base class)
Error(system or fatal errors)
Exception(regular errors)
RuntimeException(unchecked exceptions)
Lecture 4Lecture 4Slide Slide 44
Java course – IAG0040Anton Keks
Exceptions (cont)Exceptions (cont)
● Exceptions automatically collect stack trace on creation
● A method must declare all checked Exceptions it throws:
– public void hello() throws IOException {...}
– then compiler forces you to either declare 'throws' too or catch the declared exception – forced error checking
● Unchecked exceptions (extending RuntimeException) can be thrown without declaration, like NullPointerException
● Errors are never thrown from the code manually, they are fatal like OutOfMemoryError, NoClassDefFoundError
● Any Throwable can contain a nested Throwable, which caused it
– can be obtained using the getCause() method
Lecture 4Lecture 4Slide Slide 55
Java course – IAG0040Anton Keks
System propertiesSystem properties
● Provide a mean of configuration
● Handled by java.util.Properties class
● Each property is a dot-separated name-value pair:
– java.io.tmpdir=c:\\temp
● Can be read using System.getProperties() and similar methods
● Additional properties can be specified on command-line:
– java -Dproperty.name=value
● Can be stored in files with .properties extension
– load() and store() methods provided
– files are always in ISO-8859-1 (other encodings allowed in 1.6)
Lecture 4Lecture 4Slide Slide 66
Java course – IAG0040Anton Keks
Introduction to collectionsIntroduction to collections
● A Collection is a container of Objects, it groups many Objects into a single one
● Arrays are too static (but can also be considered collections)
● Arrays have very few built-in features
● Initially, Java contained a few collection classes, like Vector, Hashtable (and Properties), Stack, etc
● Java 1.2 introduced the Collections Framework
● Another example of a collections framework is the STL (Standard Template Library) in C++
Lecture 4Lecture 4Slide Slide 77
Java course – IAG0040Anton Keks
What is a Collections FrameworkWhat is a Collections Framework
The Java Collections Framework consists of:● Interfaces – abstract data types representing various
collections. Allow collections to be manipulated independently of their implementations.
● Implementations – these are the concrete implementations of the interfaces. They are reusable data structures.
● Algorithms – these are able to perform useful computations, like searching and sorting, on the implementations of the interfaces. So, the algorithms are polymorphic and therefore are reusable functionality.
Lecture 4Lecture 4Slide Slide 88
Java course – IAG0040Anton Keks
Benefits of CollectionsBenefits of Collections
● Reduce programming effort● Increase program speed and quality● Allow interoperability among unrelated APIs● Reduce effort to learn and use new APIs● Reduce effort to design new APIs● Help to reuse the code
Lecture 4Lecture 4Slide Slide 99
Java course – IAG0040Anton Keks
InterfacesInterfaces
Here are the core Collections interfaces:
Note: Collection is at the root, Map is separate
All Collections interfaces and implementation classes reside in the java.util package.
Collection
ListSet Queue
SortedSet
Map
SortedMap
Lecture 4Lecture 4Slide Slide 1010
Java course – IAG0040Anton Keks
Collection interfaceCollection interface● Is the root and the most generic one, no direct
implementations provided
● A Collection contains elements, nothing else is defined
● Operations on a Collection:
– add(...) - adds an element
– contains(...) - checks if the specified element exists
– remove(...) - removes an element
– clear() - removes all elements
– size() / isEmpty() - for checking the number of elements
– toArray() - converts the Collection to an array
– Some of the methods also operate on other Collections rather than on single elements, like addAll(...), removeAll(...), etc
Lecture 4Lecture 4Slide Slide 1111
Java course – IAG0040Anton Keks
Iterator and Iterable interfacesIterator and Iterable interfaces
● Collections can be iterated using Iterators.
● Collection interface extends Iterable, therefore any Collection can be used in 'for each' loops
● Collection provides the iterator() method, which returns the specific Iterator implementation.
● Iterator's methods:
– boolean hasNext() - returns true if there are more elements available
– Object next() - returns the next available element
– void remove() - removes the current element (optional)
● Iterators are fail-fast, they may throw ConcurrentModificationException
Lecture 4Lecture 4Slide Slide 1212
Java course – IAG0040Anton Keks
Set interfaceSet interface
● Is a mathematical set
● Contains no duplicate elements
● Some implementations may accept null element
● Set doesn't add any new methods to the Collection
● equals(...) checks for contents, implementation independent
● contains(...) is the most common use case of Sets
● SortedSet provides methods: first(), last(), headSet(), tailSet() and subSet()
Lecture 4Lecture 4Slide Slide 1313
Java course – IAG0040Anton Keks
Set implementationsSet implementations
● HashSet – the fastest implementation based on a hash table. Iteration order is not guaranteed. Addition of many new elements may be expensive due to resizing.
● TreeSet – a SortedSet, based on a red-black tree. Iteration returns elements in ascending order. Elements must be Comparable or a separate Comparator must be provided.
● LinkedHashSet – same as HashSet, but backed with a linked list and guarantees the order of iteration (defined by the insertion).
● EnumSet – specific Set for enums, implemented using bit masks, very fast and memory-efficient.
Lecture 4Lecture 4Slide Slide 1414
Java course – IAG0040Anton Keks
Set taskSet task
● Write a program, which removes all duplicate elements from an array of Strings– Name your class DuplicateRemoverImpl and put
into your own package.– Implement the
net.azib.java.collections.DuplicateRemover– Pay close attention to the javadoc– Write a main() method, which demonstrates that
the program works● Which Set implementation will you use?
Lecture 4Lecture 4Slide Slide 1515
Java course – IAG0040Anton Keks
List interfaceList interface● List is an ordered and indexed sequence of elements
– Positional access: get(...), set(...) and others
– Search: indexOf(...) and lastIndexOf(...)
– Iteration: ListIterator, which can iterate in both directions, return indexes and replace objects.
– Range-view: subList(...) returns a 'view' of a portion of the list as another List, doesn't copy. All operations on a sublist are reflected in the parent list
– add(...) appends to the end, remove(...) removes the first occurence, equals(...) checks for contents and order
● List may contain duplicate elements
Lecture 4Lecture 4Slide Slide 1616
Java course – IAG0040Anton Keks
List implementationsList implementations
● ArrayList – a List, backed by an array
– Insertions and deletions can be ineffective due to array resizing or copying of elements.
– Index based access is very effective● LinkedList – a classic linked list with the List interface
– Effective insertions, deletions and iteration– Ineffective index based access– Additional Queue, Stack or Deque functionality: addFirst(), getFirst(), removeFirst() and the same for the last element
Lecture 4Lecture 4Slide Slide 1717
Java course – IAG0040Anton Keks
Queue interfaceQueue interface
● A collection for holding elements prior to processing● Typically, a FIFO queue (but can be LIFO as well)● Implementations specify the ordering properties● New methods:
– offer() - adds the element if possible (returns false otherwise)
– poll() - retrieves and removes the element from head
– peek() - retrieves the element from head without removing it
● Java 1.6 added Deque – double ended queue
Lecture 4Lecture 4Slide Slide 1818
Java course – IAG0040Anton Keks
Queue implementationsQueue implementations
● There are many in java.util.concurrent package● LinkedList – also implements the Queue interface
– nulls are allowed
– offer() inserts at the end (tail)
– poll() and peek() operate with the first element
● PriorityQueue – a queue with prioritized elements– Only permits Comparable elements or a specific Comparator
– Head is the least element according to the comparison
– Backed by an array, nulls are not permitted
● ArrayDeque – array-backed Deque and Queue
Lecture 4Lecture 4Slide Slide 1919
Java course – IAG0040Anton Keks
Map interfaceMap interface
● Map maps keys to values (aka associative array)
● Doesn't extend Collection, but provides similar methods
– put(), get(), remove() operate with single key-value pairs
– containsKey(), containsValue() check for existense
– Collection views: keySet(), values(), entrySet()
● Map.Entry interface is for elements of a Map (key and value container)
● SortedMap is a Map with sorted keys, has analogous methods as SortedSet
Lecture 4Lecture 4Slide Slide 2020
Java course – IAG0040Anton Keks
Map implementationsMap implementations
● HashMap – the fastest implementation based on a hash table.
● TreeMap – a SortedMap, based on a red-black tree. Keys are in the ascending order.
● LinkedHashMap – a HashMap with guaranteed key iteration order.
● EnumMap – specific Map for enum keys, implemented as arrays, very fast and efficient.
● IdentityHashMap – same as HashMap, but uses '==' for equality tests instead of the equals() method, slightly faster
● WeakHashMap – very specific, holds references to keys as 'weak references', allowing garbage collector to destroy these objects while in the Map (prevents memory leaks)
Lecture 4Lecture 4Slide Slide 2121
Java course – IAG0040Anton Keks
Map taskMap task
● Write a program that calculates word frequency table in text– Text is represented by a String
● Use the s.split(“\\s”) method for parsing
– Program should output words in alphabetical order– Name your class WordFrequencyCalculator and put
into your own package– Write a main() method, which demonstrates that
the program works● Which Map implementation will you use?
Lecture 4Lecture 4Slide Slide 2222
Java course – IAG0040Anton Keks
Legacy collectionsLegacy collections● Vector
– now implements List, substituted by ArrayList
● Enumeration
– substituted by Iterator, which has shorter methods
● Stack
– now implements List, substituted by LinkedList
● Hashtable
– now implements Map, same as HashMap
● BitSet
– doesn't implement Set, a bit vector implementation, no direct substitutes in the Collections framework, but sometimes EnumSet will do the job better
Lecture 4Lecture 4Slide Slide 2323
Java course – IAG0040Anton Keks
More on implementationsMore on implementations
● Implementation classes have been discussed● There are many abstract implementations, like
AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList, etc, provided for writing new custom Collections
● Special helper classes Arrays and Collections provide additional functionality and algorithms (static methods)
Lecture 4Lecture 4Slide Slide 2424
Java course – IAG0040Anton Keks
Arrays helper classArrays helper class
● Arrays class provides operations on arrays
– asList() - provides a view of an array as a List
– binarySearch() - searches for an element from a sorted array
– equals() - checks two arrays for equality
– fill() - fills an array with the specified element
– sort() - sorts an array (using a tuned QuickSort algorithm)
– toString() - can be used for displaying of arrays
– deepToString() - the same for multidimensional arrays
Lecture 4Lecture 4Slide Slide 2525
Java course – IAG0040Anton Keks
Collections helper classCollections helper class
● Provides constants and operations on Collections
– EMPTY_XXX or emptyXXX() - immutable empty collection
– sort(), binarySearch(), fill(), copy(), min(), max(), shuffle(), replaceAll(), rotate(), swap()
– singletonXXX() - immutable collection with one element
– enumeration() - for support of legacy classes
● Wrappers
– checkedXXX() - a dynamically typesafe view
– unmodifiableXXX() - an unmodifiable view
– synchronizedXXX() - a synchronized view
Lecture 4Lecture 4Slide Slide 2626
Java course – IAG0040Anton Keks
TipsTips
● Program to interfaces
– List list = new ArrayList();
● Copy (or conversion) constructors
– Set set = new TreeSet(map.values());
● Checking if the Collection is empty
– collection.isEmpty()
– collection.size() == 0 may be very expensive
● Remove all nulls (or other elements):
– collection.removeAll(Collections.singleton(null))
● Convert to arrays
– String[] s = c.toArray(new String[c.size()]);
Lecture 4Lecture 4Slide Slide 2727
Java course – IAG0040Anton Keks
Tips (cont)Tips (cont)
● Iterate Maps with Map.Entry if you need both keys and values
– for(Map.Entry e : map.entrySet()) {}
● Initial capacity in case of HashSet, HashMap, and ArrayList
– new ArrayList(512)
● Operations on sublists are reflected in the main lists
– list.subList(15, 16).remove(object);
● All collections implement toString()
– useful for displaying the contents quickly