Your SlideShare is downloading. ×
0
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Java Advance Concepts
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Java Advance Concepts

311

Published on

Java Advance Concepts

Java Advance Concepts

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
311
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
27
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. More Features
  • 2. Garbage Collection Garbage collection is a process of managing the heapefficiently; i.e., reclaiming memory occupied byobjects that are no longer needed and making itavailable for new objects. The automatic garbage collection scheme guaranteesthat a reference to an object is always valid while theobject is needed by the program. A program has no guarantees that the automaticgarbage collector will be run during its execution.
  • 3. Garbage Collection continued An object in the heap is said to be reachable if it isreferenced by any local reference in a runtime stack. A reachable object is alive, and is accessible by one ormore live threads. Any object that is not accessible by a live thread is acandidate for garbage collection. Garbage collection does not necessarily occur as soonas an object becomes unreachable. If a composite object becomes unreachable, itsconstituent objects also become unreachable.
  • 4. Object Finalization It provides an object with a last resort to undertake any actionbefore its storage is reclaimed. The automatic garbage collector calls the finalize() method(finalizer) in an object that is eligible for garbage collectionbefore actually destroying the object. The finalize() method is defined in the Object class. Any exception thrown but not caught by a finalize method calledby the garbage collector is ignored, and the finalization of thisobject is terminated. The finalizer is only called once on an object, regardless ofwhether any exception is thrown during its execution. There is no guarantee that the finalizer will ever be called. Unlike constructors overridden finalizers are not implicitlychained.
  • 5. Invoking Garbage Collector Even though the garbage collecter can be invokedexplicitly, there are no guarantees that it will be run. The System.gc() method can be used to requestgarbage collection. System.runFinalization() method can be called tosuggest that any pending finalizers be run for objectseligible for garbage collection. Above methods are from Runtime class whose objectcan be obtained by calling the methodRuntime.getRuntime().
  • 6. Java.util package Locale class provide methods to format values thatrepresent dates, currency and numbers according to aspecific locale. Date class represents time as a long integer whichrepresents time as the date and the time of day. The Date class is not locale-sensitive, and has beenreplaced by the Calendar and Date-Format classes. A Calendar class represents a specific instant in timethat comprises a date and a time of day as in Date class It is interoperable with the Date class and manipulatedusing add(), set() and roll().
  • 7. java.text Package DateFormat class provides methods for formatting andparsing dates and time. The abstract class NumberFormat provides methods forformatting and parsing numbers and currency values. The factory methods of NumberFormat return an instanceof the concrete class java.text.DecimalFormat or aninstance of the final class java.util.Currency forformatting numbers or currency values, respectively. A number formatter can also be used to format a double ora long values. A number formatter can be used to parse strings that aretextual representations of numeric value.
  • 8. String Pattern Matching java.util.regex package provides support for string patternmatching that is based on regular expressions. The java.util.Pattern class allows to compile a regularexpression, and the java.util.Matcher class allows tocreate an engine for string pattern matching with thecompiled regular expression. A match is shown in the following notation:(start_index,end_index:group) where start_index andend_index are indices in target indicating where a patternmatch was found, and group comprises the character(s)delineated by the two indices in the target, that matchedthe pattern.
  • 9. String Pattern Matching Compiling the regular expression string into a Patternobject which constitutes the compiled representation ofthe regular expression.Pattern pattern = Pattern.compile(regexStr); Using the Pattern object to obtain a Matcher (i.e., anengine) for applying the pattern to a specified input of typejava.lang.CharSequence.Matcher matcher = pattern.matcher(input); Using the operations of the matcher to apply the pattern tothe input:boolean eureka = matcher.matches();
  • 10. Java.util.Scanner A scanner reads characters from a source and convertsthem into tokens. A token is a sequence of characters in the source thatcomprises a formatted value. It works in Tokenizing Mode, for tokenizing a stream offormatted data values and Multi-Line Mode, for searchingor finding matches in line-oriented input. It can accept input from “standard input stream” usingSystem.in and properly format the program output. The methods of the Scanner class to read input or tokenizeinput, are nextLine(), nextInt(), next(), hasNext(),hasNextIntegralType(), hasNextLine(), skip(), match() etc.
  • 11. Threads The sequence of code executed for each task defines aseparate path of execution, which is called a thread. It is an independent sequential path of execution within aprogram. Compared to processes, context switching between threadsis usually less expensive. The cost of communication between threads is relativelylow then that between the processes. Threads share the same address space, data and code. All threads are created and controlled by a unique object ofthe java.lang.Thread class in java.
  • 12. Threads The runtime environment distinguishes between user threadsand daemon threads. When an application is run, a user thread is automaticallycreated to execute the main() method which is also called themain thread. Daemon threads exist only to serve user threads. All other threads, called child threads, are spawned from themain thread, inheriting its user-thread status Calling the setDaemon(boolean) method in Thread classmarks the status of the thread as either daemon or user, but thismust be done before the thread is started. When a GUI application is started, a special thread is createdautomatically to monitor the user–GUI interaction even thoughthe main thread might have finished executing. Threads are implemented in two ways:• implementing the java.lang.Runnable interface.• extending the java.lang.Thread class.
  • 13. Runnable Interface A Runnable interface has one abstract method:public interface Runnable { void run(); } A thread created from an object implementing theRunnable interface, and will execute the code defined inpublic method run(). The procedure for creating threads using Runnableinterface is: 1. A class implements the Runnable interface,providing the run() method that will be executed by thethread. An object of this class is a Runnable object. 2. An object of the Thread class is created by passing aRunnable object as an argument in the Threadconstructor call. 3. The start() method is invoked on the Thread objectcreated in the previous step which returns immediatelyafter a thread has been spawned as start method isasynchronous.
  • 14. Constructors and methods from java.lang.Thread Thread(Runnable threadTarget) Thread(Runnable threadTarget, String threadName) The argument threadTarget is the object whose run()method is executed, and explicit name for the thread. static Thread currentThread() returns a reference to the Thread object of the currentlyexecuting thread. void run() as Thread class implements Runnable interface. final void setDaemon(boolean flag) final boolean isDaemon() Sets the status of the thread either as a daemon thread or asa user thread void start() Spawns a new thread as a child thread of the current thread
  • 15. Creating Threads from Thread Class Thread can also be created by extending Thread class. 1. A class extending the Thread class overrides therun() method from the Thread class to define the codeexecuted by the thread. 2. This subclass may call a Thread constructorexplicitly in its constructors to initialize the thread,using the super() call. 3. The start() method inherited from the Thread classis invoked on the object of the class to make the threadeligible for running.
  • 16. Synchronization A lock (also called a monitor) is used to synchronize access to ashared resource. Threads gain access to a shared resource by first acquiring thelock associated with the resource. At most one thread can hold the lock and thereby have access tothe shared resource i.e an object. A thread must acquire the object lock associated with a sharedresource to access it and restore the lock when the thread exitsthe shared resource. Classes also have a class-specific lock that is analogous to theobject lock. Two ways in which execution of code can be synchronized, eitherby declaring synchronized methods or synchronized code blocks.
  • 17. Synchronized Methods Synchronized methods of an object can be executed only by asingle thread at a time. A thread wishing to execute a synchronized method must firstobtain the object’s lock and waits if the object lock is held byanother thread. A thread relinquishes the lock simply by returning from thesynchronized method. While a thread is inside a synchronized method of an object, allother threads that wish to execute this synchronized method orany other synchronized method of the object will have to wait. Such restriction does not apply to the thread that already has thelock and is executing a synchronized method of the object. Non-synchronized methods of the object can always be called atany time by any thread. Static methods synchronize on the class lock. Synchronization of static methods in a class is independent fromthe synchronization of instance methods on objects of the class.
  • 18. Synchronized Blocks Synchronized block allows execution of arbitrary codeto be synchronized on the lock of an arbitrary object. Synchronized statement is as follows: synchronized (<object reference expression>) {<code>block> } Usually the execution of the method is synchronizedon the lock of the current object. No other thread is be able to execute the code block, orany other code requiring the object lock which isalready acquired, until the lock is relinquished.
  • 19. Thread States New state: A thread has been created, but it has notstarted yet. It starts using the start() method. Ready-to-run state: A thread starts life in the Ready-to-run state. Running state: The thread is currently executing. Dead state: Once in this state, the thread cannot ever runagain. Non-runnable states : A running thread can transit to oneof the non-runnable states, depending on thecircumstances. It remains in a non-runnable state until aspecial transition occurs. A thread first transits to theReady-to-run state before going to the Running state froma non-runnable state.
  • 20. Non Runnable States ❍ Sleeping: The thread sleeps for a specified amountof time. ❍ Blocked for I/O: The thread waits for a blockingoperation to complete. ❍ Blocked for join completion: The thread awaitscompletion of another thread. ❍ Waiting for notification: The thread awaitsnotification from another thread. ❍ Blocked for lock acquisition: The thread waits toacquire the lock of an object.
  • 21. Running and Yielding After start() method, the thread starts in the Ready-to-runstate and is eligible for running. It waits for its turn to getCPU time. Once picked by thread scheduler it goes inRunning state. A call to the method yield(), may cause the current threadin the Running state to transit to the Ready-to-run state,thus relinquishing the CPU, thus giving other threads inthe Ready-to-run state a chance to run. The thread is then at the mercy of the thread scheduler asto when it will run again, which is possible if there are nothreads in the Ready-to-run state. The yield() method is an advisory method, and comes withno guarantees that the JVM will carry out the call’s bidding. A call to the yield() method does not affect any locks thatthe thread might hold.
  • 22. Sleeping and Waking up A call to the method sleep() causes the currentlyrunning thread to temporarily pause its execution andtransit to the Sleeping state. Sleep method does not relinquish any lock that thethread might have. The thread will sleep for at least the time specified inits argument, before transitioning to the Readyto-runstate where it takes its turn to run again. If a thread is interrupted while sleeping, it will throwan InterruptedException when it awakes and gets toexecute.
  • 23. Waiting and Notifying Waiting and notifying provide means of communicationbetween threads that synchronize on the same object. Wait and Notify methods can only be executed on an objectwhose lock the thread holds (synchronized code). A thread invokes the wait() method on the object whose lock itholds, as a condition for its continued execution was not met. It leaves the Running state and transits to the Waiting-fornotification state, were it waits for the condition to occur. Such a thread relinquishes the ownership of only the object lockon which the wait() method was invoked. Each object has a wait set containing threads waiting fornotification. Hence another thread can acquire the object lock on the sharedobject for its own purposes.
  • 24. Waiting and Notifying A thread in the Waiting-for-notification state can be awakened by theoccurrence of any one of these three incidents: 1. Another thread invokes the notify() method on the object of the waitingthread, and the waiting thread is selected as the thread to be awakened. 2. The waiting thread times out. 3. Another thread interrupts the waiting thread A thread invokes a notification method on the current object whose lock itholds to notify thread(s) that are in the wait set of the object. Invoking the notify() method on an object wakes up a single thread that iswaiting for the lock of the object. The selection of a thread to awaken isdependent on the thread policies implemented by the JVM. On being notified, a waiting thread first transits to the Blocked-for-lock-acquisition state to acquire the lock on the object, and not directly to theReady-to-run state. The notifying thread relinquishes the lock at its own discretion. When the notified thread obtains the object lock, it is enabled for execution,waiting in the Ready-to-run state for its turn to execute again. Finally, when itdoes execute, the call to the wait() method returns and the thread can continuewith its execution.
  • 25. Interrupted and Joining A thread is interrupted when another thread invokedthe interrupt() method on the waiting thread. When the thread is awakened, the return from thewait() call will result in an InterruptedException if andwhen the awakened thread finally gets a chance to run. A thread can invoke the join() method on anotherthread in order to wait for the other thread to completeits execution before continuing. Thread calling join waits until other thread completesits execution, or waiting thread is timeout orinterrrupted.
  • 26. Thread Termination and Deadlocks A thread can transit to the Dead state from the Running or theReady-to-run states. The thread dies when it completes its run() method, either byreturning normally or by throwing an exception. Once in dead state, the thread cannot be resurrected. There is no way the thread can be enabled for running again, noteven by calling the start() method again on the thread object. A deadlock is a situation where a thread is waiting for an objectlock that another thread holds, and this second thread is waitingfor an object lock that the first thread holds. Since each thread is waiting for the other thread to relinquish alock, they both remain waiting forever in the Blocked-for-lock-acquisition state. It can be avoided if threads acquire locks on the objects in sameorder.
  • 27. Generics Generics allow reference types (classes, interfaces, andarray types) and methods to be parameterized with typeinformation. An abstract data type (ADT) defines both the types ofobjects and the operations that can be performed on theseobjects. Generics allow to specify the types used by the ADT, so thatthe same definition of an ADT can be used on differenttypes of objects. It provides type information in ADTs, allowing thecompiler to guarantee type-safety of operations at runtime. They are implemented as compile-time transformations. It eliminates the necessity of explicit type checking andcasting at runtime
  • 28. Generic Type A generic type is a reference type that defines a list offormal type parameters or type variables (T1, T2, ..., Tn)that must be provided before it can be used as a type. A generic class is declared as class Node<E>, which allowsnodes of specific types to be maintained, with the formaltype parameter, E, representing the type of the data in anode. If a generic class has several formal type parameters, theseare specified as a comma separated list, <T1, T2, ..., Tn>. The formal type E can be used like a reference type in theclass body: as a field type, return type, and as a parametertype in the methods.
  • 29. Formal Type Parameter A constructor declaration in a generic class cannotspecify the formal type parameters of the generic classin its constructor header after the class name. A formal type parameter E cannot be used to create anew instance, as it is not known which concrete type itrepresents. A formal type parameter is a non-static type andcannot be used in a static context.
  • 30. Parameterized types Parameterized type is an invocation or instantiation of a generictype, that is a specific usage of the generic type where the formaltype parameters are replaced by actual type parameters. In generic type invocation, the actual type parameters arepassed in order to instantiate a generic type. Generic type invocation example: Node<Integer> intNode = new Node<Integer>(2008); The actual type parameter Integer, explicitly specified in thedeclaration statement above, binds to the formal type parameterE. The compiler treats the parameterized type Node<Integer> asa new type. The parameterized type Node<Integer> constrains the generictype Node<E> to Integer objects, thus implementinghomogenous nodes with Integers. While calling a method, the actual type parameter is determinedfrom the type of the reference used to make the call.
  • 31. Generic Interface Generic interfaces is analogous to generic classes with samespecification of formal type parameters as in a genericclasses. A generic interface can be implemented by a generic (or anon-generic) class as follows: class MonoNode<E> implements IMonoLink<E> { } The first occurrence of <E> declares E to be a typeparameter, and the second occurrence of <E>parameterizes the generic interface with this typeparameter. The compiler checks that the formal type parameters of thesuperclass in the extends clause can be resolved. A subtype can inherit only one parameterization of thesame generic interface supertype.
  • 32. Raw Types A generic type without its formal type parameters is calleda raw type. The raw type is the supertype of all parameterized types ofthe generic class. A parameterized type (e.g., Node<String>) is not a classbut are used by the compiler to check that objects createdare used correctly in the program. The compiler does not create a new class for eachparameterized type and hence there is only oneimplementation of a generic class. Only reference types (excluding array creation andenumerations) can be used in invocations of generic types.
  • 33. Subtype Covariance An argument of type Node<Integer> or Node<Double> cannotbe passed where a parameter of type Node<Number> isexpected. Node<Integer> and Node<Double> are not subtypes ofNode<Number>, although Integer and Double are subtypes ofNumber. Such type relationship is called subtype covariance. The subtype covariance relationship holds for arrays because theelement type is available at runtime. The subtype covariance relationship does not hold forparameterized types that are instantiations of the same generictype with different actual type parameters, regardless of anysubtyping relationship between the actual type parameters.
  • 34. Wildcards A wildcard type can represent many types. A parameterized type that has wildcard card types as actual typeparameters can represent a family of types, in contrast to aconcrete parameterized type that only represents itself. The Subtype Covariance, ? extends Type represents all subtypesof Type (including Type itself) and is called upper boundedwildcard. Subtype Contravariance, ? super Type represents all supertypesof Type (including Type itself) and is called lower boundedwildcard. Subtype Bivariance, ? represents all types and is calledunbounded wildcard. Subtype Invariance, Type represents Type itself and is calledunbounded type parameter. There is no subtype covariance relationship between concreteparameterized types, but there is such relationship betweenbounded parameterized types and concrete parameterized types Wildcards cannot be used in instance creation expressions andcannot be used in the header of reference type declarations.
  • 35. Generic Methods and Constructors A generic method is implemented like an ordinary method,except that one or more formal type parameters arespecified immediately preceding the return type. A generic constructor has formal parameters specifiedbefore the class name in the constructor header. A formal type parameter can be used in the return type, theformal parameter list, and the method body. It can also be used to specify bounds in the formal typeparameter list. A generic method need not be declared in a generic type.
  • 36. Equals method Equals method implements the most discriminatingequivalence relation possible on objects. Each instance of the class is only equal to itself. Not overriding the equals() method appropriately makes itimpossible to search for objects in arrays, collections, ormaps. The contains() method of the list relies on the equals()method. An implementation of the equals() method must satisfythe properties of an equivalence relation such as Reflexive,Symmetric, Transitive,Consistent and null comparison.
  • 37. Hashcode Method Hashing is an efficient technique for storing and retrievingdata. A common hashing scheme uses an array where eachelement is a list of items. The array elements are calledbuckets. Operations in a hashing scheme involve computing anarray index from an item. Converting an item to its array index is done by a hashfunction. The array index returned by the hash function iscalled the hash value of the item. The hash value identifies a particular bucket.
  • 38. Hashcode method Note that no duplicate items are stored. Retrieving an item is based on using a key. The key represents the identity of the item Storing involves hashing the item to determine the bucket and if theitem does not match one already in the bucket, it is stored in thebucket. Retrieval involves hashing the key to determine the bucket and if thekey matches an item in the bucket, this item is retrieved from thebucket. Different items can hash to the same bucket. Finding an item in the bucket entails a search and requires an equalityfunction to compare items. An ideal hash function produces a uniform distribution of hash valuesfor a collection of items across all possible hash values. A hash table contains key-value entries as items and the hashing isdone on the keys only to provide efficient lookup of values. Equal objects must produce equal hash codes while inequalityplaces no restrictions on the hash value.
  • 39. The Comparable<E> Interface The natural ordering of objects is specified byimplementing the generic Comparable interface. int compareTo(E o) is the method of Comparable interfacewhich returns a negative integer, zero, or a positive integerif the current object is less than, equal to, or greater thanthe specified object. Objects implementing this interface can be used aselements in a sorted set, keys in a sorted map and elementsin lists that are sorted manually using the Collections.sort()method. The equals() and the compareTo() methods should beconsistent.
  • 40. The Comparator<E> Interface Precise control of ordering can be achieved by creatinga customized comparator that imposes a specific totalordering on the elements. int compare(E o1, E o2) method returns a negativeinteger, zero, or a positive integer if the first object isless than, equal to, or greater than the second object,according to the total ordering. An alternative ordering to the default natural orderingcan be specified by passing a Comparator to theconstructor when the sorted set or map is created.
  • 41. Java Collections Framework A collection allows a group of objects to be treated as asingle unit. Objects can be stored, retrieved, and manipulated aselements of a collection. The core framework in the java.util package comprises ofcore generic interfaces, set of implementations of coreinterfaces and an assortment of static utility methods foundin the Collections and Arrays classes. Collection (or a map) only stores reference values ofobjects, and not the actual objects. Collections are manipulated according to their interfacetypes, rather than by the implementation types.
  • 42. Core Interfaces Collection<E> is a basic interface that defines the normaloperations that allow a collection of objects to bemaintained or handled as a single unit. Set<E> extends Collection interface to represent itsmathematical namesake: a set of unique elements. E.g.HashSet<E> and LinkedHashSet<E>. SortedSet<E> extends the Set interface to provide therequired functionality for maintaining a set in which theelements are stored in some sorted order. NavigableSet<E> extends and replaces the SortedSetinterface to maintain a sorted set, and is the preferredchoice in new code. List<E> extends the Collection interface to maintain asequence of elements that can contain duplicates. E.g.ArrayList<E>, Vector<E>, LinkedList<E>.
  • 43. Core Interfaces Queue<E> extends the Collection interface to maintain acollection whose elements need to be processed in some way,i.e., insertion at one end and removal at the other, usually asFIFO. E.g. PriorityQueue<E>, LinkedList<E> Deque<E> extends the Queue interface to maintain a queuewhose elements can be processed at both ends. E.g.ArrayDeque<E>, LinkedList<E>. Map<K,V> is a basic interface that defines operations formaintaining mappings of keys to values. It does not extends thecollection interface as a Map is not a collection.HashMap<K,V>, Hashtable<K,V> andLinkedHashMap<K,V> are some implementations. SortedMap<K,V> extends the Map interface for maps thatmaintain their mappings sorted in key order. Implementationsinclude TreeMap<K, V>. NavigableMap<K,V> extends and replaces the SortedMapinterface for sorted maps. Implementations includeTreeMap<K, V>.
  • 44. Collections Frameworks
  • 45. Map Frameworks
  • 46. Collection Interface Basic operations are used to query a collection about its contentsand allow elements to be added to and removed from acollection. Basic Operations int size() boolean isEmpty() boolean contains(Object element) boolean add(E element) Optional boolean remove(Object element) Optional Array Operations allow the collections to be converted to array. Object[] toArray(): Returns array of type Object. <T> T[] toArray(T[] a): Returns array of type T.
  • 47. Collection and Iterator Interfaces Bulk operations methods performed on collection as single unit boolean containsAll(Collection<?> c) boolean addAll(Collection<? extends E> c) Optional boolean removeAll(Collection<?> c) Optional boolean retainAll(Collection<?> c) Optional void clear() Optional A collection provides an Iterator which allows sequential access to theelements of a collection. It is obtained by calling the method of theCollection interface Iterator<E> iterator() returning the objectimplementing Iterator interface. The generic interface Iterator has the methods: boolean hasNext(): Returns true if the underlying collection still haselements left to return. E next() : moves iterator to next element and returns current element. void remove() Optional : Removes the element that was returned bythe last call to the next(). When an iterator has already been obtained, structurally modifying theunderlying collection by other means will invalidate the iterator.
  • 48. Enhanced for loop for (type variable : expression) statement It sets the given type variable to each element of thecollection and then executes the statement. The value of expression can be a reference value thatrefers to a collection, an array or an object of a classthat implements the java.lang.Iterable interface. The loop variable of the “for each” loop traverses theelements of the array, not the index values.
  • 49. Sets Implementations of the Set interface do not allow duplicateelements. Its add() and addAll() methods doesn’t store duplicates. A HashSet does not guarantee any ordering of the elementswhile, the LinkedHashSet subclass of HashSet guaranteesinsertion-order. The SortedSet interface extends the Set interface to providethe functionality for handling sorted sets. The NavigableSet interface extends the SortedSet interfacewith navigation (searching) methods to find the closestmatches for specific search targets.
  • 50. SortedSet<E> Interface Methods // First-last elements E first(): gets first element in the sorted set. E last(): gets last element in the sorted set. // Range-view operations SortedSet<E> headSet(<E> toElement): returns a view of aportion of sorted set, whose elements are strictly less than thespecified element. SortedSet<E> tailSet(<E> fromElement) returns a view of aportion of sorted set, whose elements are strictly greater than thespecified element. SortedSet<E> subSet(<E> fromElement, <E> toElement):returns a view of the portion of this sorted set, whose elementsrange from fromElement, inclusive, to toElement, exclusive
  • 51. NavigableSet<E> Interface Methods // First-last elements E pollFirst(): removes and returns first element. E pollLast() : removes and returns last element. // Range-view operations NavigableSet<E> headSet(<E> toElement, boolean inclusive) NavigableSet<E> tailSet(<E> fromElement, boolean inclusive) NavigableSet<E> subSet(<E> fromElement, boolean fromInclusive, <E>toElement, boolean toInclusive) // Closest-matches E ceiling(E e): returns the least element in the navigable set. E floor(E e): returns the greatest element in the navigable set. E higher(E e): returns the least element strictly greater than argument. E lower(E e) : returns the greatest element strictly less than argument. // Reverse order Iterator<E> descendingIterator() NavigableSet<E> descendingSet()
  • 52. Lists Lists are collections that maintain their elements in order and can containduplicates. // Positional Index E get(int index): returns element at the specified index. E set(int index, E element) : replaces the element at the specified index withthe specified element returning the previous element at the specified index. // Insert or Delete void add(int index, E element) Optional boolean addAll(int index, Collection<? extends E> c) remove(int index) Optional : deletes and returns the element at the specifiedindex. // Element Search int indexOf(Object o): returns the index of the first occurrence of element. int lastIndexOf(Object o): returns index of the last occurrence of element. // Open Range-View List<E> subList(int fromIndex, int toIndex): returns a view of the list, whichconsists of the sublist of elements from the index fromIndex to index toIndex-1. // List Iterators ListIterator<E> listIterator() and ListIterator<E> listIterator(int index)
  • 53. ArrayList<E>, LinkedList<E>, Vector<E> The Vector and ArrayList classes are implemented usingdynamically resizable arrays, providing fast random access andfast list traversal. The Vector class is thread-safe, meaning that concurrent calls tothe vector will not compromise its integrity. The LinkedList implementation uses a doubly-linked list and,Insertions and deletions are very efficient. Vectors suffer a slight performance penalty due tosynchronization. Position-based access has constant-time performance for theArrayList and Vectors but is in linear time for a LinkedList. If frequent insertions and deletions occur inside a list, aLinkedList can be more efficient. LinkedList class also implements two other interfaces that allowit to be used for stacks and different kinds of queues.
  • 54. The Queue<E> Interface A queue is a collection that maintains elements in processingorder. A head position in the queue specifies where the next elementfor processing can be obtained. Queue interface has the following methods: // Insert boolean add(E element): insert the specified element. boolean offer(E element): no exception if queue full. // Remove E poll(): retrieve the head element and remove it E remove(): queue is empty, the poll() method returns null, butthe remove() method throws a NoSuchElementException. // Examine E peek(): retrieve the head element but do not remove it. E element():If the queue is empty, the peek() method returnsnull, but element() method throws NoSuchElementException.
  • 55. PriorityQueue<E> and LinkedList<E> PriorityQueue is implementation for a queue with priorityordering. The implementation is based on a priority heap, a treelikestructure that yields an element at the head of the queueaccording to the priority ordering, which is defined eitherby the natural ordering of its elements or by a comparator. In the case of several elements having the same priority,one of them is chosen arbitrarily. Elements of a PriorityQueue are not sorted. The queue only guarantees that elements can be removedin priority order, and any traversal using an iterator doesnot guarantee to abide by the priority order.
  • 56. The Deque<E> Interface he Deque interface extends the Queue interface to allow double-ended queues. It allows operations not just at its head, but also at its tail. It is a linear unbounded structure in which elements can beinserted at or removed from either end. The Deque interface defines symmetrical operations at its headand tail such as offerFirst() and offerLast(). The ArrayDeque class provides better performance than theLinkedList class for implementing FIFO queues, and is a betterchoice than java.util.Stack class for implementing stacks. An ArrayDeque is also Iterable, and traversal is always from thehead to the tail while descendingIterator() method for iteratingin reverse order.
  • 57. Maps A Map defines mappings from keys to values. The <key, value> pair is called an entry. A map does not allow duplicate keys and each keymaps to one value at the most, implementing a single-valued map. Both the keys and the values must be objects. The Map interface does not extend the Collectioninterface. The Map interface specifies some optional methods.
  • 58. Map interface basic methods Object put(K key, V value) Optional : inserts the <key,value> entry into the map. Object get(Object key): returns the value to which thespecified key is mapped, Object remove(Object key) Optional: deletes the entryfor the specified key returning value of the key. boolean containsKey(Object key): returns true if thespecified key is mapped to a value in the map. boolean containsValue(Object value): returns true ifexists one or more keys that are mapped to specified value. int size(): return the number of entries (unique keys). boolean isEmpty(): whether the map is empty or not.
  • 59. Maps: Bulk and View Operations void putAll(Map<? extends K, ? extends V> map) Optional: copiesall entries from the specified map to the current map void clear() Optional: deletes all entries from the current map. Following methods return a set view of keys, a collection view of values,and a set view of <key, value> entries, respectively. 1) Set<K> keySet() 2) Collection<V> values(): (does not return a Set) 3) Set<Map, Entry<K, V>> entrySet() An entry in the entry set view can be manipulated by methods definedin the interface, which are selfexplanatory: interface Entry<K, V> {K getKey();V getValue();V setValue(V value);}
  • 60. HashMap<K,V>, LinkedHashMap<K,V> andHashtable<K,V> The classes HashMap and Hashtable implement unorderedmaps. The class Linked-HashMap implements ordered maps. The class TreeMap implements sorted maps. While the HashMap class is not thread-safe and permits one nullkey, the Hashtable class is thread-safe and permits non-null keysand values only. The LinkedHashMap implementation is a subclass of theHashMap class. The elements in a LinkedHashSet are in (element) insertionorder and also maintains its elements in (element) access order. Adding, removing, and finding entries in a LinkedHashMap canbe slightly slower than in a HashMap.
  • 61. SortedMap<K,V>, NavigableMap<K,V> Interfacesand TreeMap<K,V> Class SortedMap interface extends the Map interface to providethe functionality for implementing maps with sorted key. Operations of SortedMap interface include get First-lastkeys and range views such as headMap(),tailMap() andsubMap(). NavigableMap interface extends the SortedMap interfacewith navigation methods to find the closest matches forspecific search targets. Treemap class provides an implementation that sorts itsentries in a specific order by implementing NavigableMapinterface. By default in the Treemap class, operations on sorted mapsrely on the natural ordering of the keys while a totalordering can be specified by passing a customizedcomparator to the constructor.
  • 62. Operations on Collections Ordering Elements in Lists <E extends Comparable<? super E>> void sort(List<E> list) <E> void sort(List<E> list, Comparator<? super E> c) <E> Comparator<E> reverseOrder() <E> Comparator<E> reverseOrder(Comparator<E>comparator) void reverse(List<?> list) void rotate(List<?> list, int distance) void shuffle(List<?> list) void swap(List<?> list, int i, int j)
  • 63. Searching and Changing Elementsin Collections Searching in Collections <E> int binarySearch(List<? extends Comparable<? super E>> list, Ekey) <E> int binarySearch(List<? extends E> list, E key, Comparator<? super E> c)) int indexOfSubList(List<?> source, List<?> target) int lastIndexOfSubList(List<?> source, List<?> target) Changing Elements in Collections <E> boolean addAll(Collection<? super E> collection, E... elements) <E> void copy(List<? super E> destination, List<? extends E> source) <E> void fill(List<? super E> list, E element) <E> boolean replaceAll(List<E> list, E oldVal, E newVal) <E> List<E> nCopies(int n, E element)
  • 64. Sorting and Searching Arrays Sorting Arrays void sort(type[] array) void sort(type[] array, int fromIndex, int toIndex) <E> void sort(E[] array, Comparator<? super E> comp) <E> void sort(E[] array, int fromIndex, int toIndex, Comparator<? super E> comp) Searching in Arrays int binarySearch(type[] array, type key) int binarySearch(type[] array, int fromIndex, int toIndex, typekey) <E> int binarySearch(E[] array, E key, Comparator<? super E>c) <E> int binarySearch(E[] array, int fromIndex, int toIndex, Ekey, Comparator<? super E> c)
  • 65. Creating List Views andMiscellaneous Utilities Creating List Views of Arrays <E> List<E> asList(E... elements) Miscellaneous Utility Methods in the Arrays Class void fill(type[] a, type val) void fill(type[] a, int fromIndex, int toIndex, type val) String toString(type[] a) String deepToString(Object[] a)
  • 66. Collections /MapsInterface Duplicates Ordered/ Sorted Methods called onelementsData StructureImplementedHashSet<E> Set<E> UniqueelementsNo order equals()hashCode()Hash table, linkedlistLinkedHashSet<E>Set<E> UniqueelementsInsertionorderequals()hashCode()Hash tableDoublyLinkListTreeSet<E> SortedSet<E>,NavigableSet<E>UniqueelementsSorted compareTo() Balanced treeArrayList<E> List<E> Allowed Insertion order equals() Resizable arrayLinkedList<E> List<E>Queue<E>Deque<E>Allowed Insertion/priority/Deque orderequals()compareTo()Linked listVector<E> List<E> Allowed Insertion order equals() Resizable arrayPriority-Queue<E>Queue<E> Allowed Access accordingto priority ordercompareTo() Priority heapArrayDeque<E> Queue<E>Deque<E>Allowed Access according toFIFO or LIFOProcessing Orderequals() Resizable arrayHashMap<K,v> Map<K,V> UniquekeysNo order equals()hashCode()Hash table usingarrayLinkedHashMap<K,V>Map<K,V> UniquekeysKey insertion order/Access order of Entriesequals()hashCode()Hash table anddoubly-linkedlistHashtable<K,V> Map<K,V> UniquekeysNo order equals()hashCode()Hash tableTreeMap<K,V> SortedMap<K,V>NavigableMap<K,V>UniquekeysSorted in key order equals()compareTo()Balanced tree

×