SlideShare a Scribd company logo
1 of 27
Download to read offline
Java course - IAG0040




             Exceptions,
             Collections


Anton Keks                           2011
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 often

Java course – IAG0040                                                     Lecture 4
Anton Keks                                                                  Slide 2
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 4
Anton Keks                                                          Slide 3
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

Java course – IAG0040                                                  Lecture 4
Anton Keks                                                               Slide 4
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 4
Anton Keks                                                            Slide 5
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 4
Anton Keks                                                                Slide 6
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 4
Anton Keks                                                         Slide 7
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 code



Java course – IAG0040                          Lecture 4
Anton Keks                                       Slide 8
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 4
Anton Keks                                             Slide 9
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(...), etc
Java course – IAG0040                                                Lecture 4
Anton Keks                                                            Slide 10
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.
●   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
Java course – IAG0040                                            Lecture 4
Anton Keks                                                        Slide 11
Set 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()

Java course – IAG0040                                    Lecture 4
Anton Keks                                                Slide 12
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 4
Anton Keks                                                    Slide 13
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 4
Anton Keks                                             Slide 14
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, 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
Java course – IAG0040                                                Lecture 4
Anton Keks                                                            Slide 15
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 element
Java course – IAG0040                                    Lecture 4
Anton Keks                                                Slide 16
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 queue

Java course – IAG0040                                            Lecture 4
Anton Keks                                                        Slide 17
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 Queue
Java course – IAG0040                                            Lecture 4
Anton Keks                                                        Slide 18
Map 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



Java course – IAG0040                                          Lecture 4
Anton Keks                                                      Slide 19
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 4
Anton Keks                                                    Slide 20
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 4
Anton Keks                                                 Slide 21
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
      –   doesn't implement Set, a bit vector implementation, no direct
          substitutes in the Collections framework, but sometimes EnumSet will
          do the job better
Java course – IAG0040                                                  Lecture 4
Anton Keks                                                              Slide 22
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 4
Anton Keks                                            Slide 23
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 arrays


Java course – IAG0040                                         Lecture 4
Anton Keks                                                     Slide 24
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 view


Java course – IAG0040                                            Lecture 4
Anton Keks                                                        Slide 25
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 4
Anton Keks                                                Slide 26
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




Java course – IAG0040                                               Lecture 4
Anton Keks                                                           Slide 27

More Related Content

Viewers also liked

Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerAnton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionAnton Keks
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIAnton Keks
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to AgileAnton Keks
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: IntroductionAnton Keks
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOPAnton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingAnton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsAnton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure JavaAnton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database RefactoringAnton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design PatternsAnton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyAnton Keks
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 

Viewers also liked (13)

Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 

Similar to Java Course 4: Exceptions & Collections (20)

Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Collections
CollectionsCollections
Collections
 
Collections in java
Collections in javaCollections in java
Collections in java
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
 
Cse java
Cse javaCse java
Cse java
 
Unit3 packages & interfaces
Unit3 packages & interfacesUnit3 packages & interfaces
Unit3 packages & interfaces
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 

Recently uploaded

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Recently uploaded (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

Java Course 4: Exceptions & Collections

  • 1. Java course - IAG0040 Exceptions, Collections Anton Keks 2011
  • 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 often Java course – IAG0040 Lecture 4 Anton Keks Slide 2
  • 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 4 Anton Keks Slide 3
  • 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() method Java course – IAG0040 Lecture 4 Anton Keks Slide 4
  • 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 4 Anton Keks Slide 5
  • 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 4 Anton Keks Slide 6
  • 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 4 Anton Keks Slide 7
  • 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 code Java course – IAG0040 Lecture 4 Anton Keks Slide 8
  • 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 4 Anton Keks Slide 9
  • 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(...), etc Java course – IAG0040 Lecture 4 Anton Keks Slide 10
  • 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. ● 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 Java course – IAG0040 Lecture 4 Anton Keks Slide 11
  • 12. Set 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() Java course – IAG0040 Lecture 4 Anton Keks Slide 12
  • 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 4 Anton Keks Slide 13
  • 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 4 Anton Keks Slide 14
  • 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, 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 Java course – IAG0040 Lecture 4 Anton Keks Slide 15
  • 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 element Java course – IAG0040 Lecture 4 Anton Keks Slide 16
  • 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 queue Java course – IAG0040 Lecture 4 Anton Keks Slide 17
  • 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 Queue Java course – IAG0040 Lecture 4 Anton Keks Slide 18
  • 19. Map 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 Java course – IAG0040 Lecture 4 Anton Keks Slide 19
  • 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 4 Anton Keks Slide 20
  • 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 4 Anton Keks Slide 21
  • 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 – doesn't implement Set, a bit vector implementation, no direct substitutes in the Collections framework, but sometimes EnumSet will do the job better Java course – IAG0040 Lecture 4 Anton Keks Slide 22
  • 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 4 Anton Keks Slide 23
  • 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 arrays Java course – IAG0040 Lecture 4 Anton Keks Slide 24
  • 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 view Java course – IAG0040 Lecture 4 Anton Keks Slide 25
  • 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 4 Anton Keks Slide 26
  • 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 quickly Java course – IAG0040 Lecture 4 Anton Keks Slide 27