Wednesday, October 16, 2013

UDDI: Universal Description, Discovery, and Integration


I recently found out about this protocol I never heard of, so I decided to write a post about it to share it with you.

If you want to implement a Service Oriented Architecture UDDI will help a lot to implement it, most of the Enterprise Service Bus solutions that are in the market implement this protocol.

Introduction

UDDI is a standard for publishing and discovering information about web services, it behaves as a directory service for describing services, discovering businesses, and integrating business services. 
It defines a group of Web services and programmatic interfaces for publishing, retrieving, and managing information about services. (In true SOA fashion, a UDDI registry is itself composed of Web services!) 

It is a protocol developed by OASIS, It  focuses on the process of discovery in the service-oriented architecture, so most of the Enterprise Service Bus implements this standard.

UDDI registry can have three types of information white pages, yellow pages and green pages:

  • White pages: Basic contact information and identifiers, such as business name, address. 

  • Yellow pages: Information that describes a web service using different categorizations, such as business type manufacturing.

  • Green pages: Technical information that describes the behaviors and supported functions of a web service hosted by your business.

Developers use the UDDI to publish services and query the registry to discover services matching various criteria., they can query one or more UDDI registries to view the different businesses that expose web services and the specifications of those services.

Architecture

The UDDI Business Registry (UBR) or the Public Cloud, is built from multiple nodes that has their data synchronized through replication, so each node has the same information.

Content inserted into the UBR is done at a single node, and that operator node becomes the master owner of that content. Any subsequent updates or deletes of the data must occur at the operator node where the data was inserted.





Private nodes can be created too forming a private cloud, these nodes do not have data synchronized with the UBR they just have information replicated between them.

Specifications

UDDI builds upon several other established industry standards, including HTTP, XML, XML Schema (XSD), SOAP, and WSDL.




UDDI defines a set of XML Schema definitions that describe the data formats used by the various specification APIs.
UDDI Version 3.0.2 XML Schema. UDDI uses the XML Schema Language to formally describe its data structures. UDDI Version 3.0.2 XML Schema is provided by these files:

UDDI Version 3.0.2 WSDL Service Interface Descriptions. The complete set of UDDI Version 3.0.2 WSDL definitions is provided by these files:
What you can do with these documents:

UDDI replication

This document describes the data replication processes and interfaces to which a registry operator must conform to achieve data replication between sites. This specification is not a programmer's API; it defines the replication mechanism used among UBR nodes.

UDDI operators

This document outlines the behavior and operational parameters required by UDDI node operators. This specification defines data management requirements to which operators must adhere. For example, node operators are responsible for durable recording and backup of all data, ensuring that each business registration has a valid email address associated with it, and the integrity of the data during deletions (e.g., deleting a business means that all of its service entries must also be deleted). This document is not a programmer's API and private registries are not required to support it.

UDDI Programmer's API

This specification defines a set of functions that all UDDI registries support for inquiring about services hosted in a registry and for publishing information about a business or a service to a registry. This specification defines a series of SOAP messages containing XML documents that a UDDI registry accepts, parses, and responds to. This specification, along with the UDDI XML API schema and the UDDI Data Structure specification, makes up a complete programming interface to a UDDI registry.

UDDI data structures

This specification covers the specifics of the XML structures contained within the SOAP messages defined by the UDDI Programmer's API. This specification defines five core data structures and their relationships to one another.

So this is a brief introduction to UDDI protocol so in case you heard of it you can know what is all about.

Monday, August 19, 2013

JAVA EE SERVERS

JAVA EE SERVERS

I recently notice that Jboss changed the name of its community server version from JBoss AS to Wildfly. It took me some time to understand what was all the fuzz about, first I thought it was a new server but then I finally get it, Red hat was just making a bigger distinction between the JBoss supported (Jboss EAP) and community (now Wildfly) version nothing else, just like red hat and fedora.
You can find more information about it in the following link:

With this I realized that there are plenty versions of JEE servers in the market and is hard to understand for a non expert or a newbie which one does what and what is the difference between all of them, so I decided to write a post about the JEE Servers that are available, just to list some of its features and not a benchmark because that would require expertise in each server and I don't have that.

Before getting into serves here is a list of the specifications that a full Java EE 7 server should have, I will refer to it in a future as figure 1.







































Apache Tomcat 


Apache tomcat is an open source web server, it has many years in the market and is very common to find implementations using it.
Tomcat is a web server because it supports the Java Servlet and JavaServer Pages and others related to them, the table below shows the specification version supported by the tomcat version.

Tomcat home page: http://tomcat.apache.org/



Jetty


Jetty is a open source web container, it an Eclipse project and is hosted entirely at the Eclipse Foundation. It is known for be a lightweight server and be easily embedded in devices, tools, frameworks, application servers, and clusters. It has support for SPDY, WebSocket, OSGi, JMX, JNDI, JAAS and many other integrations.

The specifications that jetty has support are:
















More information about jetty can be found in the following link:


Apache TomEE




Apache TomEE is an open source Java EE 6 Web Profile server, it is based on Tomcat with EE features, that's the reason of its name “TomEE” pronounced as "Tommy”. It is practically new its first release came out in April of 2012, but it is gaining popularity and it has the support of the apache community.

TomEE server supports more JEE specifications than tomcat such as Enterprise JavaBeans, Java Persistence API (JPA), and others. It comes in different packages each with different specifications, the following table shows a comparison of the different packages.



















TomEE uses other project to provide the specifications:
  • CDI - Apache OpenWebBeans
  • EJB - Apache OpenEJB
  • JPA - Apache OpenJPA
  • JSF - Apache MyFaces
  • JSP - Apache Tomcat
  • JSTL - Apache Tomcat
  • JTA - Apache Geronimo Transaction
  • Servlet - Apache Tomcat
  • Javamail - Apache Geronimo JavaMail
  • Bean Validation - Apache BVal
  • JAX-RS - Apache CXF
  • JAX-WS - Apache CXF
  • JMS - Apache ActiveMQ
  • Connector - Apache Geronimo Connector


Use the following link for more information:


Glassfish


Glassfish is an open source Java EE application server sponsored by Oracle, it works as a reference implementation of the latest Java EE specifications. Its latest version Glassfish 4 supports the Java EE 7 specifications, so it should support all the specifications shown in figure 1.

 It makes use of some others opens source projects to implement the specifications:












Also Oracle provides a commercial version of this server which offers support. The following links will provide more information.



Geronimo



Apache Geronimo is an open source server, it is Java EE 6 certified and it is based in OSGI offering a more modular design.

Geronimo also uses other source projects to implement the specifications:
  • OpenEJB
  • OpenJPA
  • ActiveMQ
  • Tomcat
  • Jetty
  • TranQL


In the following link you can find a list of all the components or projects used in geronimo:

Geronimo home page:





JBoss Wildfly and Jboss AS



Wildfly formerly JBoss AS is an open source Java EE server now sponsored by Red Hat. Wildfly is still in alpha version but it would've be the Jboss AS 8 version. It supports the Java EE 7 specifications shown in “figure 1”, and it is based in OSGI offering a more modular design.

It makes use of some others opens source projects to implement the specifications, such as:


Red hat also offers a commercial version of Wildfly named JBoss EAP and it has all the benefits of a commercial product such as support, extra tools and many others. Its fees are not cheap it will probably cost tens of thousand of dollar, so be careful at the time of choosing a commercial server, the following link is a calculator from RED HAT so you can get an idea about the fees http://www.redhat.com/promo/eap_calculator/

Some of the links where you can find more information about Jboss are:



Weblogic



Oracle WebLogic Server is a commercial Java EE application server, its latest version is weblogic 12 is a Java EE 6 Full Profile, so the Java EE 6 specifications are supported. The following image shows the platforms supported by Weblogic.


















As it is commercial counterpart from redhat, oracle provides support and many tools for maintain the server, but is not a cheap server it will probably cost tens of thousand of dollar also. The following link is a pdf about the costs so you can get an idea about the fees:

Some of the links where you can find more information about Weblogic are:


Websphere 


IBM WebSphere Application Server is a commercial Java EE application server, its latest version is WebSphere 8, it is JEE6 certiļ¬ed based in OSGI offering a more modular design, some of the features they include are:

● Enterprise JavaBeans (EJB) 3.1
● Java Servlet 3.0
● Contexts and Dependency Injection for Java (CDI) 1.0
● Bean Validation 1.0
● Java Architecture for XML Binding (JAXB) 2.2
● Enterprise Web Services 1.3
● Java API for XML-Based Web Services (JAX-WS) 2.2

The Operative Systems supported are:




















As it is commercial as Weblogic and JBoss EAP, it comes with all the benefits from a commercial product but also its fees, the following image shows how much could it cost to have Webshpere:








In the following link more information about websphere can be found:

FUJITSU

FUJITSU Software Interstage Application Server is a commercial server and support standards such as Java EE, Web Service, and CORBA. Interstage Application Server component technologies and development frameworks.

It has support for the following features:
























The OS supported are:
  • Microsoft Windows Server 2008 R2
  • Microsoft Windows Server 2008
  • Microsoft Windows Server 2003 R2
  • Microsoft Windows Server 2003
  • Windows Azure Guest OS 1.18~(4)
  • Windows Azure Guest OS 2.6~(4)
  • Red Hat Enterprise Linux 6
  • Red Hat Enterprise Linux 5
  • Solaris 11
  • Solaris 10

For more information about fujitsu server go to the following links:

JEUS

TmaxSoft's JEUS is a commercial Java EE certified application server. It supports the following specifications:



















JEUS offer support for clustering, load balancing and has tools for the development and administration process.

For more information about JEUS go to the following link:




JONAS


OW2 Jonas is an open source Java EE application server, it is Java EE 5 certified and has a Java EE 6 preview version, is based in OSGI offering a more modular design.

Jonas use other opens source projects to implement the specifications, and since it is based on osgi different options and you can choose what project to use:















OW2 do not offer a commercial version of Jonas server but it offers a support subscription for professional support and training, it has tools for managing and clustering but they are for free.

In the following link more information about JONAS can be found:



Resin 


Resin is a commercial Java application server by Caucho, it supports the Java EE 6 Web Profile. It supports Servlet, JSP, JSTL, EJB, Candi (Java CDI), JSF, JPA, and more. It is a lightweight server designed with CDI.It has Java monitoring and OS monitoring facilities available via built-in console or third party applications via JMX and REST



















It has support for clustering and tools for application deployment, distributed caching, load balancing and messaging, and so on.

Resin can be used with Amazon Web Services for cloud deployment. More information about resin and amazon can be found in the following link:

The prices of the licenses of resin can be found in the following link:

Resin has an open source version http://resin.caucho.com/ , the differences between the open source and the commercial version, is the amount of tools offered by the commercial version, in the following link a comparison between the two versions can be found:

For more information about resin go to the following link:

Well these are the most known options that can be found for a JEE server, I try to list some of its features and useful links. As I said before this is not a benchmark, but for choosing one server first you have to check if you want a commercial option or open source option, then check what options are among between your budget and then evaluate these options, its features, the support, if it is open source the community support, the documentation and so on.

And finally here is a link where you can find which servers are compatible with each JEE profile:


Sunday, August 4, 2013

Java Collections Framework Part 7 - Collections Utility

Collections Utility class
The java.util.Collections class is an utility class, an utility class defines a set of static methods that perform common operations, all the methods of Collections are public and static.

The java API says about the Collection class “This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends”.

The Collections class has methods for changing the order of lists:

void reverse(List<?> list): Reverses the order of the elements
void rotate(List<?> list, int distance): Rotates the elements in the specified list by the specified distance.
void shuffle(List<?> list): Randomly permutes the list elements
void shuffle(List<?> list, Random rnd): Randomly permutes the list using the randomness source rnd
<T extends Comparable<? super T>> void sort(List<T> list): Sorts the supplied list using natural ordering
<T> void sort(List<T> list, Comparator<? super T> c): Sorts the supplied list using the supplied ordering
void swap(List<?> list, int i, int j): Swaps the elements at the specified positions

It has methods for changing the contents of a list, the copy() transfers elements from the source list into an initial a the destination list, the fill() replaces every element of a list with a specified object and replaceAll() replaces every occurrence of one value in a list with another.

<T> void copy(List<? super T> dest, List<? extends T> src): Copies all of the elements from one list into another
<T> void fill(List<? super T> list, T obj): Replaces every element of list with obj
<T> boolean replaceAll(List<T> list, T old, T new): Replaces all occurrences of old in list with new.

It has methods for finding elements in ordered collections:

<T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll): Returns the maximum element using natural ordering.
<T> T max(Collection<? extends T> coll, Comparator<? super T> comp): Returns the maximum element using the supplied comparator
<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll): Returns the minimum element using natural ordering
<T> T min(Collection<? extends T> coll, Comparator<? super T> comp): Returns the minimum element using the supplied comparator
<T> int binarySearch(List<? extends Comparable<? super T>> list, T key): Searches for key using binary search
<T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c): Searches for key using binary search
int indexOfSubList(List<?> source, List<?> target): Finds the first sublist of source which matches target
int lastIndexOfSubList(List<?> source, List<?> target): Finds the last sublist of source which matches target

Some methods require that the collection should be ordered before using them otherwise their outcome will make no sense, this is the case of the binarySearch(), if the list is not ordered then the binarySearch() will return a wrong value, Example:


In the example you can see how the collection is ordered before using the binarySearch() method.

Some methods are overloaded with a version that takes a Comparator, in this case the type of the Collection doesn't have to implement the Comparable interface, Example:


In the example you can see that the List is of type Person and it doesn't implements the Comparable interface but at the time to order the collection and search it, a Comparator instance is used it.

The Collections class has methods for creating collections:

<T> List<T> emptyList(): Returns the empty list (immutable)
<K,V> Map<K,V> emptyMap(): Returns the empty map (immutable)
<T> Set<T> emptySet(): Returns the empty set (immutable)

These methods can be used to indicate there are no values, the collections returned by this methods are immutable, this means no elements can be added to them.

Example:

The previous example will throw a java.lang.UnsupportedOperationException at the time the new element was added.

There are also methods for creating collections containing only a single element.

<T> Set<T> singleton(T o): Returns an immutable set containing only the specified object.
<T> List<T> singletonList(T o): Returns an immutable list containing only the specified object.
<K,V> Map<K,V> singletonMap(K key, V value): Returns an immutable map, mapping only the key K to the value V

The collections returned by this methods are also immutable and no elements can be added to them.

Example:


The previous example will throw a java.lang.UnsupportedOperationException at the time the new element was added.

There is a method that creates a list containing a number of copies of a given object.

<T> List<T> nCopies(int n, T o): Returns an immutable list containing n references to the object o

Sometimes a collection implementation is not synchronized, in order to make a collection thread safe the Collections class provides methods for this purpose:

<T> Collection<T> synchronizedCollection(Collection<T> c);
<T> Set<T> synchronizedSet(Set<T> s);
<T> List<T> synchronizedList(List<T> list);
<K, V> Map<K, V> synchronizedMap(Map<K, V> m);
<T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s);
<K, V> SortedMap<K, V> synchronizedSortedMap(SortedMap<K, V> m);

Basically this last post is a summary of the java.util.Collections class, but if I was doing a tutorial about collections I had to add it. So with this I finish the tutorial and I hope you can find a quick reference to the collections API and learn something new.




Saturday, July 27, 2013

Java Collections Framework Part 6 - Queues

This is the sixth part of the tutorial, and this link goes to the previous post java collections framework part 5

Queues

A queue is a collection that implements the interface java.util.Queue , usually a queue is an ordered collection that follows the FIFO (First-In, First-Out) rule, but the queue implementations allow other ways to order the collection as well, such as LIFO or based on priority and so on.



The Queue interface defines the following methods:

boolean add(E e): Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
E element(): Retrieves, but does not remove, the head of this queue.
Boolean offer(E e): Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions.
E peek(): Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
E poll(): Retrieves and removes the head of this queue, or returns null if this queue is empty.
E remove(): Retrieves and removes the head of this queue.

Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.

PriorityQueue

The class java.util.PriotiyQueue is an implementation of the Queue interface, it is an ordered collection and allows duplicates, it works as a “Priority-In, Priority-Out” collection, its elements are ordered by priority and its default priority is given by its natural order, it can be defined another priority order with an instance of a Comparator.

Example


The previous example should print the elements in the collection according to its priority, in this case it should print 1 2 3 4 5 6 7 8 9, this means they priority is the natural order.

To specify a different priority an instance of a Comparator should be used:

Example

The previous example should print its elements according to the new priority specified at the time the collection was created, this new priority is the inverse of the natural order and the example should print 9 8 7 6 5 4 3 2 1

Deque

The java.util.Deque interface extends the Queue interface, the deque name means “double-ended queue”. In a double-ended queue elements can be inserted and removed at both ends of the queue, unlike queue that elements only can be inserted at the tail and removed at the head.
With this a deque can also act as a LIFO collection or Stack.



The Deque interface defines new methods besides the ones defined in the Queue interface:

void addFirst(E e) : Inserts e at the head if there is enough space
void addLast(E e): Inserts e at the tail if there is enough space
void push(E e): Inserts e at the head if there is enough space
boolean removeFirstOccurrence(Object o): Removes the first occurrence of o
boolean removeLastOccurrence(Object o): Removes the last occurrence of o
Iterator<E> descendingIterator(): Gets an iterator that returns the elements in reverse order
boolean offerFirst(E e): Inserts e at the head if the deque has space
boolean offerLast(E e): Inserts e at the tail if the deque has space
E peekFirst(): Gets but do not removes the first element
E peekLast(): Gets but do not removes the last element
E pollFirst(): Gets and removes the first element
E pollLast(): Gets and removes the last element
E getFirst(): Gets but do not removes the first element
E getLast(): Gets but do not removes the last element
E removeFirst(): Gets and removes the first element
E removeLast(): Gets and removes the last element
E pop(): Gets and removes the first element

Example


In the previous example a deque collection was created and elements were added in different ways, first the elements were added at the head so the collection final order was:

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

The the elements were added to the tail the collection final order was:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

And this is also the default behavior for adding elements, in the example were used methods for querying the head and the tail of the collection. The example should print:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
9
0

LinkedList

The class java.util.LinkedList besides being a List also implements the Deque interface, this class is very popular because with one class many different behaviors can be implemented.

Go to part 7




Sunday, July 21, 2013

Java Collections Framework Part 5 - Maps

This is the sixth part of the tutorial, and this link goes to the previous post java collections framework part 4

Maps

A Map implements the java.util.Map interface, this interface doesn't extends from the Collection interface. A map is a collection of key-value mappings, they don't allow duplicate keys and like Sets, maps rely on the equals() method to determine whether two keys are the same or different.

Maps do not have order but some implementations are sorted like the TreeMap.

Maps like the Collection interface have methods for adding and removing elements, querying collection contents, and providing different views of the contents of a collection, and some of this methods are:

V put(K key, V value): Add or replace a key-value association, returns the old value (may be null) if the key was present; otherwise returns null.
void putAll(Map<? extends K,? extends V> m): Adds each of the key-value associations in the supplied map into the receiver.
void clear(): Removes all associations from this map.
V remove(Object key): Removes the association, if any, with the given key; returns the value with which it was associated, or null.
V get(Object k): Returns the value corresponding to k, or null if k is not present as a key.
boolean containsKey(Object k): Returns true if k is present as a key.
boolean containsValue(Object v): Return true if v is present as a value.
int size(): Returns the number of mappings.
boolean isEmpty(): Returns true if there are no mappings.
Set<Map.Entry<K, V>> entrySet(): Returns a Set view of the associations.
Set<K> keySet(): Return a Set view of the keys
Collection<V> values(): Return a Collection view of the values

The java.util.HashMap class is an implementation of the Map interface. HashMap it keeps its elements unsorted and unordered.

You should know that HashMap allows one null key and multiple null values in a collection.


Example:


In the previous example a HashMap of Integers as keys and Strings as values was created, five elements were added and then an element was added again replacing its previous value. The output of the example should be:

Map:{[1, one] [2, two] [3, three-again] [4, four] [5, five] }

The java.util.Hashtable class is also an implementation of the Map interface and it is almost identical
to the HashMap class but it is synchronized so it performs slower than HashMap and another difference is that Hashtable doesn't let you have anything that's null.

The java.util.LinkedHashMap class extends from the HashMap class and therfore is an Implementation of the Map interface, and as the LinkedHashSet class the LinkedHashMap it maintains insertion order (or, optionally, access order). Access ordered is defined by the argument of of the constructor:

public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder)

A value false will give an insertion-ordered map, if order constructor is used to create the LinkedHashMap by default it would be an insertion-ordered map.

Example:


The output of the example should be the following:
Map { [1-1] [2-2] [3-3] [4-4] [5-5] }

Changing the the iteration order for an access order in the previous example:


Notice that after adding the elements an access to the element “1” is done with this the iteration order is changed and the output should be the following:
Map Keys { [2] [3] [4] [5] [1] }
Also notice that the output format has changed and now just the keys are printed, this is because if the element is obtained inside the iteration loop a ConcurrentModificationException would arise because the iteration order is changed , and this can not be done while the map is iterated. So be careful when the Map is in this mode.

TreeMap

The class java.util.TreeMap is an implementation of the Map interface, it also implements the
java.util.NavigableMap and java.util.SortedMap interfaces. This collection is pretty similar to TreeSet, it is an sorted collection and guarantees that the keys will be in ascending order, according to their natural order, or by a Comparator provided at map creation time, depending on which constructor is used.

The TreeMap class implements methods that help navigate the map, and some of these methods are:

K ceilingKey(key): Returns the lowest key >= key
K higherKey(key): Returns the lowest key > key
K floorKey(key): Returns the highest key <= key
K lowerKey(key): Returns the highest key < key
Map.Entry<K,V> pollFirstEntry(): Returns and removes the first key-value pair
Map.Entry<K,V> pollLastEntry(): Returns and removes the last key-value pair
NavigableMap<K,V> descendingMap(): Returns a NavigableMap in reverse order
NavigableSet<K> descendingKeySet(): Returns a reverse-order key set
NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive):Returns a part of the map whose keys range from fromKey to toKey.
NavigableMap<K,V> headMap(K toKey, boolean inclusive):Returns a part of the map whose keys are less than toKey.
NavigableMap<K,V> tailMap(K fromKey, boolean inclusive):Returns a part of the map whose keys are greater than or equal to fromKey.

Example:


The example should print in console the following:
keys: [1, 2, 3, 4, 5]
Ceiling: 3
Higher: 4
Floor: 3
Lower: 2
Descending keys: [5, 4, 3, 2, 1]
Head map: {1=one, 2=two}
Tail map: {1=one, 2=two}
Poll first: 1=one
Poll last: 5=five
keys: [2, 3, 4]

You can notice how the elements in the map are printed in ascending order, but the map can also be iterated in descending order with the method descendingKeySet().
The sub maps obtained with the methods headMap(), tailMap() and others are backed maps ant hey behave just like any other backed collection this is if submap is modified then also the map is modified
and viceversa.



Sunday, July 14, 2013

Java Collections Framework Part 4 - Sets

This is the sixth part of the tutorial, and this link goes to the previous post  java collections framework part 3

Sets

A Set implements the interface java.util.Set, it has the same methods as those of the Collection interface.
Sets do not accept duplicate elements, if the add() method is called with an object that already is in the set it should return false. The elements of the set must have a good implementation of the equals() method.

There are different implementations of the Set interface they can have order, can be sorted, or neither this is they can be unordered and unsorted.

HashSet

The class java.util.HashSet is an implementation of the Set interface, it is not sorted and it doesn't have an order. If the hashset is iterated it states that it does not guarantee that the order will remain constant over time.

The elements of this type of set must implement the the hashcode() and the equals() methods, this is because it is implemented as a hash table in which elements are stored at a position derived from their contents. So, Two elements are considered equal or duplicate if they return the same hash code from the hashcode() method and they return true from testing them with the equals() method.

The Set first gets the hash code from the element then places the element in a bucket of the hash table for that hash code, if the bucket already has an element then it tests for duplicity the elements with their equals().


Example:


In the previous example the Element class has two implementations of the hashcode() method one that uses the hashcode of its value attribute of type String and other that generates random integers, if the implementation that uses the String is used then the Set would not accept duplicate elements this is because same strings should generate the same hashcode so the ouptut with this implementation should not contain any duplicate element as this:
[3, 2, 1, 4]
But if the implementation that generates random integer is used then the Set would accept duplicate elements because it would be placing each element in a different bucket of its hash table, the output would be something like this:.
[3, 2, 1, 4, 1]

LinkedHashSet

The class java.util.LinkedHashSet extends from the class HashSet and therefore is an implementation of the Set interface. LinkedHashSet is hash table and a doubly-linked list, it has an order, its iterators will return their elements in the order in which they were added.
The LinkedHashSet doesn't define any new method, it just adds the linked functionality to the HashSet class.



Example:


In the previous example the output should in the order in which the elements were added, so it should print this:
[ 6, 5, 3, 4, 1, ]

TreeSet

The class java.util.TreeSet is an implementation of the Set interface, it also implements the java.util.NavigableSet and java.util.SortedSet interfaces, it is an sorted collection and guarantees that the elements will be in ascending order, according to their natural order, or by a Comparator provided at set creation time, depending on which constructor is used.

The TreeSet class implements methods that help navigate the set, and some of these methods are:

ceiling(e): Returns the lowest element >= e
higher(e): Returns the lowest element > e
floor(e): Returns the highest element <= e
lower(e): Returns the highest element < e
pollFirst(): Returns and removes the first entry
pollLast(): Returns and removes the last entry
NavigableSet  descendingSet(): Returns a NavigableSet in reverse order

Example:


The example should print
First:1
Last:5
Higher:4
Lower:2
Ceiling:3
Floor:3

The TreeSet class also has more methods that return section of its collection, some of this methods are:

NavigableSet headSet(e, b*): Returns a subset ending at element e and exclusive of e
NavigableSet tailSet(e, b*): Returns a subset starting at and inclusive of element e
NavigableSet subSet(s, b*, e, b*): Returns a subset starting at element s and ending just before element e

The collections that return this methods are backed collections, this means when an element is added to the original or to the backed collection, the new entries were automatically added to the other collection

Example:


The example should print
Set: [a, b, c, d, g]
Sub set: [c, d]
Set: [a, b, c, d, e, g]
Sub set: [c, d, e]
Note that the subset was modified and also the set is modified, this is because subset is a backed collection of the set.

Go to part 5