SlideShare a Scribd company logo
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

What's hot

Troubleshooting Network and Network Utilities
Troubleshooting Network and Network UtilitiesTroubleshooting Network and Network Utilities
Troubleshooting Network and Network Utilities
Rubal Sagwal
 
Understanding NMAP
Understanding NMAPUnderstanding NMAP
Understanding NMAP
Phannarith Ou, G-CISO
 
Fundamentals of network performance engineering
Fundamentals of network performance engineeringFundamentals of network performance engineering
Fundamentals of network performance engineering
Martin Geddes
 
Snmp
SnmpSnmp
Threat modeling web application: a case study
Threat modeling web application: a case studyThreat modeling web application: a case study
Threat modeling web application: a case study
Antonio Fontes
 
Integrated Tools in OSSIM
Integrated Tools in OSSIMIntegrated Tools in OSSIM
Integrated Tools in OSSIM
AlienVault
 
Introduction to Open Mano
Introduction to Open ManoIntroduction to Open Mano
Introduction to Open Mano
videos
 
Nmap
NmapNmap
Nmap basics
Nmap basicsNmap basics
Nmap basics
itmind4u
 
Understanding Cisco’ Next Generation SD-WAN Technology
Understanding Cisco’ Next Generation SD-WAN TechnologyUnderstanding Cisco’ Next Generation SD-WAN Technology
Understanding Cisco’ Next Generation SD-WAN Technology
Cisco Canada
 
The-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdf
The-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdfThe-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdf
The-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdf
prasunkagrawal
 
Best Network Performance Monitoring Tool
Best Network Performance Monitoring ToolBest Network Performance Monitoring Tool
Best Network Performance Monitoring Tool
Joe Shestak
 
Brocade Administration & troubleshooting
Brocade Administration & troubleshootingBrocade Administration & troubleshooting
Brocade Administration & troubleshooting
prakashjjaya
 
66 pfsense tutorial
66 pfsense tutorial66 pfsense tutorial
66 pfsense tutorial
equinonesr
 
Penetration testing & Ethical Hacking
Penetration testing & Ethical HackingPenetration testing & Ethical Hacking
Penetration testing & Ethical Hacking
S.E. CTS CERT-GOV-MD
 
Non functional performance requirements v2.2
Non functional performance requirements v2.2Non functional performance requirements v2.2
Non functional performance requirements v2.2
Ian McDonald
 
SPAN, RSPAN and ERSPAN
SPAN, RSPAN and ERSPANSPAN, RSPAN and ERSPAN
SPAN, RSPAN and ERSPAN
NetProtocol Xpert
 
Ppt of routing protocols
Ppt of routing protocolsPpt of routing protocols
Ppt of routing protocols
Bhagyashri Dhoke
 
Firewall presentation
Firewall presentationFirewall presentation
Firewall presentation
Amandeep Kaur
 
NATS for Rubyists - Tokyo Rubyist Meetup
NATS for Rubyists - Tokyo Rubyist MeetupNATS for Rubyists - Tokyo Rubyist Meetup
NATS for Rubyists - Tokyo Rubyist Meetup
wallyqs
 

What's hot (20)

Troubleshooting Network and Network Utilities
Troubleshooting Network and Network UtilitiesTroubleshooting Network and Network Utilities
Troubleshooting Network and Network Utilities
 
Understanding NMAP
Understanding NMAPUnderstanding NMAP
Understanding NMAP
 
Fundamentals of network performance engineering
Fundamentals of network performance engineeringFundamentals of network performance engineering
Fundamentals of network performance engineering
 
Snmp
SnmpSnmp
Snmp
 
Threat modeling web application: a case study
Threat modeling web application: a case studyThreat modeling web application: a case study
Threat modeling web application: a case study
 
Integrated Tools in OSSIM
Integrated Tools in OSSIMIntegrated Tools in OSSIM
Integrated Tools in OSSIM
 
Introduction to Open Mano
Introduction to Open ManoIntroduction to Open Mano
Introduction to Open Mano
 
Nmap
NmapNmap
Nmap
 
Nmap basics
Nmap basicsNmap basics
Nmap basics
 
Understanding Cisco’ Next Generation SD-WAN Technology
Understanding Cisco’ Next Generation SD-WAN TechnologyUnderstanding Cisco’ Next Generation SD-WAN Technology
Understanding Cisco’ Next Generation SD-WAN Technology
 
The-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdf
The-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdfThe-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdf
The-Hacker-Playbook-Practical-Guide-To-Penetration-Testing-2014.pdf
 
Best Network Performance Monitoring Tool
Best Network Performance Monitoring ToolBest Network Performance Monitoring Tool
Best Network Performance Monitoring Tool
 
Brocade Administration & troubleshooting
Brocade Administration & troubleshootingBrocade Administration & troubleshooting
Brocade Administration & troubleshooting
 
66 pfsense tutorial
66 pfsense tutorial66 pfsense tutorial
66 pfsense tutorial
 
Penetration testing & Ethical Hacking
Penetration testing & Ethical HackingPenetration testing & Ethical Hacking
Penetration testing & Ethical Hacking
 
Non functional performance requirements v2.2
Non functional performance requirements v2.2Non functional performance requirements v2.2
Non functional performance requirements v2.2
 
SPAN, RSPAN and ERSPAN
SPAN, RSPAN and ERSPANSPAN, RSPAN and ERSPAN
SPAN, RSPAN and ERSPAN
 
Ppt of routing protocols
Ppt of routing protocolsPpt of routing protocols
Ppt of routing protocols
 
Firewall presentation
Firewall presentationFirewall presentation
Firewall presentation
 
NATS for Rubyists - Tokyo Rubyist Meetup
NATS for Rubyists - Tokyo Rubyist MeetupNATS for Rubyists - Tokyo Rubyist Meetup
NATS for Rubyists - Tokyo Rubyist Meetup
 

Viewers also liked

Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
Anton Keks
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
Anton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
Anton Keks
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
Anton Keks
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
Anton Keks
 
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
Anton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
Anton Keks
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
Anton Keks
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
Anton Keks
 
Java Course 1: Introduction
Java Course 1: IntroductionJava Course 1: Introduction
Java Course 1: Introduction
Anton Keks
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
Anton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
Anton Keks
 
Java Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, AssertionsJava Course 5: Enums, Generics, Assertions
Java Course 5: Enums, Generics, Assertions
Anton Keks
 
Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
Anton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton 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 Streams
Anton Keks
 

Viewers also liked (18)

Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Java Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & EncodingsJava Course 7: Text processing, Charsets & Encodings
Java Course 7: Text processing, Charsets & Encodings
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 
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

Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Singsys Pte Ltd
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
saryu2011
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
Łukasz Wójcik
 
Collections
CollectionsCollections
Collections
bsurya1989
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Collections in java
Collections in javaCollections in java
Collections in java
kejpretkopet
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
Khizar40
 
Collection framework
Collection frameworkCollection framework
Collection framework
BindhuBhargaviTalasi
 
Java tutorials
Java tutorialsJava tutorials
Collections and generic class
Collections and generic classCollections and generic class
Collections and generic class
ifis
 
Cse java
Cse javaCse java
Unit3 packages & interfaces
Unit3 packages & interfacesUnit3 packages & interfaces
Unit3 packages & interfaces
Kalai Selvi
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
Woxa Technologies
 
Scala ntnu
Scala ntnuScala ntnu
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
Woxa Technologies
 

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

IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
IPLOOK Networks
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
alexjohnson7307
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
shyamraj55
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
ankush9927
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
bellared2
 
Feature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptxFeature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptx
ssuser1915fe1
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
bhumivarma35300
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Kunal Gupta
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
Jimmy Lai
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
Ivanti
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Muhammad Ali
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
SynapseIndia
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
Baishakhi Ray
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
BrainSell Technologies
 
Mastering OnlyFans Clone App Development: Key Strategies for Success
Mastering OnlyFans Clone App Development: Key Strategies for SuccessMastering OnlyFans Clone App Development: Key Strategies for Success
Mastering OnlyFans Clone App Development: Key Strategies for Success
David Wilson
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
SubhamMandal40
 

Recently uploaded (20)

IPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite SolutionIPLOOK Remote-Sensing Satellite Solution
IPLOOK Remote-Sensing Satellite Solution
 
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
leewayhertz.com-AI agents for healthcare Applications benefits and implementa...
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
 
Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10Computer HARDWARE presenattion by CWD students class 10
Computer HARDWARE presenattion by CWD students class 10
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
 
Feature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptxFeature sql server terbaru performance.pptx
Feature sql server terbaru performance.pptx
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptxUse Cases & Benefits of RPA in Manufacturing in 2024.pptx
Use Cases & Benefits of RPA in Manufacturing in 2024.pptx
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
 
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdfAcumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
Acumatica vs. Sage Intacct vs. NetSuite _ NOW CFO.pdf
 
Mastering OnlyFans Clone App Development: Key Strategies for Success
Mastering OnlyFans Clone App Development: Key Strategies for SuccessMastering OnlyFans Clone App Development: Key Strategies for Success
Mastering OnlyFans Clone App Development: Key Strategies for Success
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
 

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