Collections Interface

 

Main portion of collection java.util.Collection<E> is event lies on generics. The <E> depends on users wrapper class choice.  Collections interface does guarantee the following methods:

  • add and addAll
  • clear
  • contains and containsAll
  • equals and hashCode
  • isEmpty
  • iterator
  • remove, removeAll and retainAll
  • size
  • toArray

A few examples of collection interface applications are;

  • Set
  • List
  • Map

Set:  The Set collection is known as that does not hold list of values in a sequence, in this sort of collection the only importance is to have the members

Examples

Hashset: The order does not matter

TestMain.java

public class TestMain {

	public static void main(String[] args) {
		Set<String> set = new HashSet<>();
		set.add("Java");
		set.add("C++");
		set.add("C#");
		set.add("Cold Fusion");
		set.add("Mathlab");
		set.add("PHP");
		System.out.println("Set list size size: " + set.size());
		for(String obj : set){
			System.out.println(obj);
		}
	}

}

Output

Set list size size: 6
C#
PHP
Cold Fusion
C++
Mathlab
Java

Treeset: it sorts all elements out

public class TestMain {

	public static void main(String[] args) {
		Set<String> set = new TreeSet<>();
		set.add("Java");
		set.add("C++");
		set.add("C#");
		set.add("Cold Fusion");
		set.add("Mathlab");
		set.add("PHP");
		System.out.println("Set list size size: " + set.size());
		for(String obj : set){
			System.out.println(obj);
		}
	}

}

Output

Set list size size: 6
C#
C++
Cold Fusion
Java
Mathlab
PHP

List: The list collection holds all the values in an ordered list moreover it can keep duplicate non-redundant data this is one of difference between List and Set and second of all, List however can be indexed by their position

Map: The map collection enables you to iterate through the list using one item to use as an index. The major difference between Map and List is that List you need an integer to get the item at the regarding index, but in Map only an object needed to locate and grasp the item at the value. Map takes two parameters one Key which is used for the index and the second parameter is the value stored in the map. We can hold values of objects in values in Map

Example

class Lang {
	private String name;
	private Integer year;

	public Lang(String name, Integer year) {
		super();
		this.name = name;
		this.year = year;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getYear() {
		return year;
	}

	public void setYear(Integer year) {
		this.year = year;
	}

	@Override
	public String toString() {
		return "Lang [name=" + name + ", year=" + year + "]";
	}

}

public class TestMain {

	public static void main(String[] args) {
		Map<String, Lang> listOfLanguages = new HashMap<>();
		listOfLanguages.put("First", new Lang("C++", new Integer(1983)));
 listOfLanguages.put("Second", new Lang("Ada", new Integer(1980)));
 listOfLanguages.put("Third", new Lang("Java", new Integer(1995)));

		System.out.println("Second langugage on list is: "
				+ listOfLanguages.get("Second"));

		for (Lang obj : listOfLanguages.values()) {
			System.out.println(obj);
		}
	}
}

Output using Hashmap:

Second langugage on list is: Lang [name=Ada, year=1980]
Lang [name=Java, year=1995]
Lang [name=Ada, year=1980]
Lang [name=C++, year=1983]

Output using TreeMap:

Second langugage on list is: Lang [name=Ada, year=1980]
Lang [name=C++, year=1983]
Lang [name=Ada, year=1980]
Lang [name=Java, year=1995]

 

Q&A Special

What is special about an EnumSet? [1]

1) EnumSet is a special Set implementation, only applicable for Enums in Java, but you can only store instances of single enum type. Adding instance of different enum will result in compile time error, as EnumSet provide type-safety.

2) EnumSet internal representation is extremely efficient and represented as bit vectors. Library itself chooses one of two implementation available depending upon size of key universe. RegularEnumSet is chosen if number of instances is less than 64, otherwise JumboEnumSet is used.

3) As described in Effective Java, EnumSet can be safely used as type safe alternative of traditional int based “bit flags”. EnumSet provides much needed readability, without compromising performance.

4) Iterator returned by EnumSet traverse the elements in their natural order, i.e. the order on which enum constants are declared, or the order returned by ordinal() method.

5) EnumSet iterator is weekly consistent and never throws ConcurrentModificationException, and may or may not show effect of any modification to the Set, while iteration is in progress.

6) EnumSet is also not synchronized in Java. Though if you need, you can make EnumSet synchronized similar to other collection by using utility methods from Collections class. Here is how to do that :

Set<YourEnum> s = Collections.synchronizedSet(EnumSet.noneOf(YourEnum.class));

7) EnumSet is an abstract class, which means you cannot create its instance using new() operator. This is actually carefully thought to provide special implementation, and that’s why EnumSet provides several static factory methods for creating instance e.g. noneOf() returns an empty EnumSet with specified enum type, EnumSet.of(….) returns Set of specified enum constants and allOf() method creates an enum set containing all elements of specified enum.

8) EnumSet also provides methods like complementOf(EnumSet es) and copyOf(EnumSet es) to create EnumSet from other EnumSet, coplementOf() returns enum set with containing all the elements of this type that are not contained in the specified set.

What features does a CopyOnWriteArraySet possess? [2]

CopyOnWriteArraySet is little brother of CopyOnWriteArrayList class. These are special purpose collection classes which was added on JDK 1.5, along with their most popular cousin ConcurrentHashMap. They are part of concurrent collection framework and reside in java.util.concurrent package. CopyOnWriteArraySet is best suited as read-only collection whose size is small enough to copy if some mutative operation happens, for example you can use CopyOnWriteArraySet to store object at start-up of application and let multiple application thread access them during application life time. If an new condition or object comes up during that time, it can also be added into this Set, with incurring cost of creating a new array. One of the most important thing to know about CopyOnWriteArraySet is that it is backed by CopyOnWriteArrayList, which means it also share all basic properties of CopyOnWriteArrayList. Another important thing to remember is that Iterators of this collection class doesn’t support remove() operation, trying to remove an element while iterating will result in UnSupportedOperationException. This is done to ensure speed during traversal, traversing this set implementation using Iterator is fast and cannot encounter interference from other threads. Iterators actually rely on unchanging snapshots of the array at the time the iterators were constructed. In short, use CopyOnWriteArraySet if set is small enough to copy on add, set or remove, and main purpose is to read data with occasional updates. Also if you want to remove elements during iteration, don’t use this Set implementation because its iterator doesn’t support remove(), and throws java.lang.UnsupportedOperationException

Although a Set does not, in general, guarantee an order on elements, what does the TreeSet guarantee? [3]

TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in sorted, ascending order.

 

 

 

References

1. http://javarevisited.blogspot.com.tr/2014/03/how-to-use-enumset-in-java-with-example.html

2. http://javarevisited.blogspot.com.tr/2014/06/how-to-use-copyonwritearrayset-in-java-example-tutorial.html

3. http://www.tutorialspoint.com/java/java_treeset_class.htm

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *