Showing posts with label java collection tutorial. Show all posts
Showing posts with label java collection tutorial. Show all posts

Wednesday, April 9, 2014

For Each loop Puzzle in Java

From Java 5 onwards, we have a for-each loop for iterating over collection and array in Java. For each loop allows you to traverse over collection without keeping track of index like traditional for loop, or calling hasNext() method in while loop using Iterator or ListIterator. For-each loop indeed simplified iteration over any Collection or array in Java, but not every Java programmer is aware of some useful details of for-each loop, which we will see in this tutorial. Unlike other popular items from Java 5 release alias Generics, Autoboxing and variable arguments, Java developers tend to use for-each loop more often than any other feature, but when asked about how does advanced foreach loop works or what is basic requirement of using a Collection in for-each loop, not everyone can answer. This small tutorial and example aims to bridge that gap by going through some interesting foreach loop puzzles. So, without any further delay let's see our first puzzle on Java 5 for-each loop.
Read more �

Monday, March 31, 2014

How to use EnumSet in Java with Example

EnumSet is one of the specialized implementation of Set interface for enumeration type, introduced in Java 1.5 along with enumeration type itself. Programmer often stores Enum into common collection classes e.g. HashSet or ArrayList, mostly because they are unaware of this little gem. Even I wasn't aware of this class few years ago, until I come across one of the finest book for Java programmers, Effective Java. It has an Item on EnumSet, which highlight some typical use-cases for this collection class instead of using int variable and bitwise operator. Since Enum constants are unique and has pre-defined length, as you can not define a new enum constant at runtime; it allows Java API designer to highly optimize EnumSet. If you look closely, EnumSet also teaches you couple of good design practices to create flexible and maintainable code. For example, EnumSet is an abstract class, and it provides lots of static factory method to create instance of EnumSet e.g. EnumSet.of(...). This method takes advantage of method overloading and variable argument to provide Set of only provided Enum constants. Second good thing is there are two concrete sub-classes of EnumSet e.g. RegularEnumSet and JumboEnumSet, but both are package-private, which means client can not use them directly. Only way to use them is via EnumSet. At runtime, depending upon key size of requested Enum, implementation automatically decide which implementation to use. This provides you immense flexibility and control to rollout a new better version of EnumSet implementation without any change on client side. Anyway, this article is not just about design lessons form this class but more importantly how and when to use EnumSet in Java program. I have shared simple example to demonstrate power of EnumSet, which you will see in next section.
Read more �

Friday, March 21, 2014

Binary Search vs Contains Performance in Java List

There are two ways to search an element in a List class, by using contains() method or by using Collections.binarySearch() method. There are two versions of binarySearch() method, one which takes a List and Comparator and other which takes a List and Comparable. This method searches the specified list for the specified object using the binary search algorithm. The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If List is not sorted, then results are undefined. If the List contains multiple elements equal to the specified object, there is no guarantee which one will be returned. This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). If the specified list does not implement the RandomAccess interface and is large, this method will do an iterator-based binary search that performs O(n) link traversals and O(log n) element comparisons. In the end this method returns the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. This means that return value will be >= 0 if and only if the key is found. Since common implementation of List interface e.g. ArrayList, Vector, CopyOnWriteArrayList and Stack implements RandomAccess interface, they can be used for performing binary search, but there are other implementations like LinkedList, which doesn't implement java.util.RandomAccess, hence not suitable for binary search operation. Since binary search can only be performed in sorted list, you also need to sort your collection before doing search, which may potentially impact performance, especially if your List is big and not in sorted order already.
Read more �

Wednesday, October 2, 2013

What is PriorityQueue or priority queue data structure in Java with Example - Tutorial

PriorityQueue is an unbounded Queueimplementation in Java, which is based on priority heap. PriorityQueue allows you to keep elements in a particular order, according to there natural order or custom order defined by Comparator interface in Java. Head of priority queue data structure will always contain least element with respect to specified ordering. For example, in this post, we will create a PriorityQueue of Items, which are ordered based upon there price, this will allow us to process Items, starting from lowest price. Priority queue is also very useful in implementing Dijkstra algorithm in Java. You can use to PriorityQueue to keep unsettled nodes for processing. One of the key thing to remember about PriorityQueue in Java is that it's Iterator doesn't guarantee any order, if you want to traverse in ordered fashion, better use Arrays.sort(pq.toArray()) method. PriorityQueue is also not synchronized, which means can not be shared safely between multiple threads, instead it's concurrent counterpart PriorityBlockingQueue is thread-safe and should be used in multithreaded environment. Priority queue provides O(log(n)) time performance for common enqueing and dequeing methods e.g. offer(), poll() and add(), but constant time for retrieval methods e.g. peek() and element().
Read more �

Friday, August 16, 2013

How to Sort List in reverse Order in Java Collection Framework with Example

Java Collection Framework provides a convenient reverse comparator, to sort List of objects in reverse order. You can obtain reverse Comparator, by calling Collections.reverseOrder(), which by default sort List of Integer in reverse numeric order and List of String in reverse alphabetic order. It actually reverse natural ordering of objects imposed by Comparable interface. Apart from this method, Collections class also provides an overloaded method Collections.reverseOrder(Comparatorcmp), which takes a Comparator, and sort List on reverse order of that Comparator. So next time if you need to sort your Collection in reverse order, you don�t need to write any extra comparator by yourself, you can directly leverage reverse comparator provided by java.util.Collections class. It is as simple as calling Collections.sort() method providing comparator wrapped into Collections.reverseOrder() method. By using these two methods, you can sort any Listimplementation e.g. ArrayList, LinkedListor Vectorin Java.
Read more �