Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java Course 4: Exceptions & Collections

7,024 views

Published on

Lecture 4 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures: https://github.com/angryziber/java-course

Published in: Technology

Java Course 4: Exceptions & Collections

  1. 1. Java course - IAG0040 Exceptions, CollectionsAnton Keks 2011
  2. 2. java.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 oftenJava course – IAG0040 Lecture 4Anton Keks Slide 2
  3. 3. Exceptions● 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: Exception RuntimeException (regular errors) (unchecked exceptions) Throwable (base class) Error (system or fatal errors)Java course – IAG0040 Lecture 4Anton Keks Slide 3
  4. 4. 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() methodJava course – IAG0040 Lecture 4Anton Keks Slide 4
  5. 5. System 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)Java course – IAG0040 Lecture 4Anton Keks Slide 5
  6. 6. Introduction 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++Java course – IAG0040 Lecture 4Anton Keks Slide 6
  7. 7. What 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.Java course – IAG0040 Lecture 4Anton Keks Slide 7
  8. 8. Benefits 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 codeJava course – IAG0040 Lecture 4Anton Keks Slide 8
  9. 9. Interfaces Here are the core Collections interfaces: Collection Set List Queue Map SortedSet SortedMap Note: Collection is at the root, Map is separate All Collections interfaces and implementation classes reside in the java.util package.Java course – IAG0040 Lecture 4Anton Keks Slide 9
  10. 10. Collection 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(...), etcJava course – IAG0040 Lecture 4Anton Keks Slide 10
  11. 11. Iterator 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.● Iterators 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 ConcurrentModificationExceptionJava course – IAG0040 Lecture 4Anton Keks Slide 11
  12. 12. Set interface ● Is a mathematical set ● Contains no duplicate elements ● Some implementations may accept null element ● Set doesnt 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()Java course – IAG0040 Lecture 4Anton Keks Slide 12
  13. 13. Set 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.Java course – IAG0040 Lecture 4Anton Keks Slide 13
  14. 14. Set 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?Java course – IAG0040 Lecture 4Anton Keks Slide 14
  15. 15. List 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, doesnt 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 elementsJava course – IAG0040 Lecture 4Anton Keks Slide 15
  16. 16. List 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 elementJava course – IAG0040 Lecture 4Anton Keks Slide 16
  17. 17. Queue 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 queueJava course – IAG0040 Lecture 4Anton Keks Slide 17
  18. 18. Queue 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 QueueJava course – IAG0040 Lecture 4Anton Keks Slide 18
  19. 19. Map interface ● Map maps keys to values (aka associative array) ● Doesnt 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 SortedSetJava course – IAG0040 Lecture 4Anton Keks Slide 19
  20. 20. Map 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)Java course – IAG0040 Lecture 4Anton Keks Slide 20
  21. 21. Map 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?Java course – IAG0040 Lecture 4Anton Keks Slide 21
  22. 22. Legacy 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 – doesnt implement Set, a bit vector implementation, no direct substitutes in the Collections framework, but sometimes EnumSet will do the job betterJava course – IAG0040 Lecture 4Anton Keks Slide 22
  23. 23. More 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)Java course – IAG0040 Lecture 4Anton Keks Slide 23
  24. 24. Arrays 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 arraysJava course – IAG0040 Lecture 4Anton Keks Slide 24
  25. 25. Collections 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 viewJava course – IAG0040 Lecture 4Anton Keks Slide 25
  26. 26. Tips ● 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()]);Java course – IAG0040 Lecture 4Anton Keks Slide 26
  27. 27. 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 quicklyJava course – IAG0040 Lecture 4Anton Keks Slide 27

×