Skip to main content

Java Collection Framework

Comes under java.util from java 1.2. before collections vector stack properties classes used to manipulate group of objects. Collections has bring these all to an unified theme and following goals.
1. High performance. Dynamic arrays, linked list, trees, hash table are high efficient.
2. Different collections must work in similar manner with high interoperability.
3. Extending and adapting must me easy. So this is built on few standard interfaces like linked list, hash set, tree set. Own implementations supported too.
4. Allowing integration of standard arrays to collections framework.

Algorithms defines static methods to manipulate collections.
Iterators allows standard way of accessing collection elements one at a time.(enumeration)
Spliterator introduced in Java 8 to provide support for parallel iteration. It has nested interfaces to support primitive types.

Jdk 5 added following to collections
Genetics
Auto boxing/ un boxing
For each loop

Generics added type safety to the collections. Before it was possible to have runtime type mismatches.
Auto boxing in boxing allows storing primitive types in collections. Before it has to be done manually.
Iterator interface allows iterator based for each looping.

Collection Interfaces

Collection - allows working with group of objects.
Deque - for double ended queues. Can be queue or stack. Has push pop methods.
List - for list of objects
NavigableList - searchable elements
Queue - elements removed from the head only. First in first out.
Set - contains unique elements
SortedSet - for sorted sets ascending

Also use the
Comparator - to compare objects
Random Access - to elements
Iterator, List Iterator, spliterator - to enumerate

Collection interfaces allow modify content using optional methods. Called modifiable. Unmodifiable collections can't be changed.

interface Collection<E>

Must be implemented by any class that defines a collection. This extend iterable interface.
UnsupportedOperationException when collection can't be modified. ClassCastException when objects incompatible. IllegalStateException when the collections is full.
ParallelStream() supports parallel processing. Steam () supports sequential processing.

Collection Classes

Generally not synchronized, but it's possible. Core classes are, linkedList, ArrayDeque, AbstractQueue, hashSet.

ArrayList
Extends AbstractList and implements List interface. Is a dynamic array can grow. It has a initial size, or can set manually. Capacity increasing involves re allocations which is time costly. Can reduce this if we know the required capacity using ensureCapacity() method to set minimum. TrimToSize() to reduce.  Can be converted to an array using <T> T[] toArray(T array[]).

Collections can store references but not primitive types.  But auto boxing may automatically wrap them in objects.

LinkedList
Extends AbstractSequentialList and implements List Deque and queue. Is a generic class provides linked list data structure.

HashSet
Creates a collection that uses a hash table for storage with hashing. A hash code is generated from the value to use as a index. Hashing increases the performance. This is not sorted.
Output may vary. LinkedHashSet maintains the order the elements were inserted.

TreeSet
Implements Navigable interface. Uses a tree for sorting. Sorted in ascending order. Read write is very fast.

PriorityQueue
Prioritizes the queue based on queues comparator. If no comparator is set, data type will be used and ordered in ascending order. So great of the queue will be the smallest.
Capacity grows automatically.

Accessing via Iterator

Iterator enables you to cycle through a collection, obtaining or removing elements. Extended ListIterator allows bidirectional traversal of a list and modification of elements.
Some method are remove set nextIndex forEachRemaining.
Iterator<String> itr = myArrayList.iterator();
While (itr.hasNext()){
String element = itr.next();
}
If you won't be modifying the contents or traversing reverse, it's more convenient to use for-each loop.

Spliterators

Is a new Iterator introduced in jdk 8, offers more functionalities than Iterator or ListIterator. It supports parallel iterations, thus supports parallel programming. It also combines hasNext and next methods with forEachRemaining. Several sub interfaces to use with primitive types doubles int and long.

While(mySpIterator.tryAdvance((n) -> system.out.println(n)))

mySpIterator.forEachRemaining((n) ->system.out.println(n))))

Storing User defined classes
Is supported by collection framework.

RandomAccess Interface
No members but it signals it supports random access to elements efficiently. This is implemented by ArrayList.

Working with Maps

Map stores key value pairs, can find a value by key. Maps ideally does not allow for each style loop as it doesn't implement Iterable interface. Get and put are the main operations.
Following method is used to get the collection view of map.
EntrySet() returns elements
KeySet() keys
Values ()

Sorted maps ensure elements are in ascending order based on keys. Allows efficient manipulation of sub maps. Sub maps are obtained by headmap () trailmap () or submap () methods.

WeakHashMap uses weak keys, allows element to be garbage collected when not used. HashMap users hash table to store the map, optimise read write times. Hash maps does not maintain the order. TreeMaps are sorted and read write are faster as it implements Navigable interface. LinkedHashMap maintain the insertion order.

Comparators

By default ordering happens with natural ordering, a before b, 1 before 2 and so forth. If you need a different ordering way you must use a comparator. Before Java 8 only supported methods were equals and compare. Some new method are
reverseOrder(),
naturalOrder()
nullsFirst() consider null as less
nullsLast()
thenComparing() when 1st round matches second level of comparing
comparing()  returns comparator that obtains it's comparison key from a function passed in.

TreeSet<String> ts = new TreeSet<String>((aStr, bStr) -> bStr.compareTo(aStr) );

Checked methods such as checkedCollection() returns dynamically type safe view of the collection.

Arrays
binarySearch() to sorted arrays.
copyOf(sourceArray, length) this will add nulls zeros or truncated if the length doesn't match.
copyOfRange() copy a range from array
equals () returns true if arrays are equal.
deepEquals() for nested arrays.
fill() assigns default value to all elements
parallelSort() in java 8 speeds up sorting time.
Java8 supports spliterators and streams. Java8 parallelPrefix() modifies each element of the array to contain cumulative operation value.

Legacy classes and interfaces

Modern collection classes duplicates old java.util class logics. But all legacy classes are synchronized while collections not. But they can make synchronized easily.

Enumeration
Allows obtain one at a time from a collection of objects. Iterators are used instead of enumerations in New code.

Vector
Vector implements dynamic array. Similar to ArrayList but two differences: synchronised and contains legacy methods.
Default size of a vector is 10 unless specified the size. When the length is reached size is doubled unless incremental size is not defined.

Stack
Is a sub class of Vector that implements last in first out stack. Has following methods
Empty - true if empty
Peek - returns top element without removing
Pop - removes and return top element
Push - adds new to top and returns the same
Search - returns the off set from top

ArrayDeque is better than stack.

Dictionary
An abstract class that represents a key value storage repository and operates like a map.
Use maps instead.

Hashtable
Implementation of dictionary. Similar to hashMap but synchronised. No null values supported. Key is hashed using the key.
Hash table can only store objects that override hashcode and equal methods. Hashcode must compute and return hash code for the object.

Properties
Subclass of hash table. Key and value both are strings. Can set a default value.
Set x = mypropertyobject.keyset() can use to iterate through list.
Properties can be stored or load from disk with store () or load ()

Comments

Popular posts from this blog

Oracle Database 12c installation on Ubuntu 16.04

This article describes how to install Oracle 12c 64bit database on Ubuntu 16.04 64bit. Download software  Download the Oracle software from OTN or MOS or get a downloaded zip file. OTN: Oracle Database 12c Release 1 (12.1.0.2) Software (64-bit). edelivery: Oracle Database 12c Release 1 (12.1.0.2) Software (64-bit)   Unpacking  You should have following two files downloaded now. linuxamd64_12102_database_1of2.zip linuxamd64_12102_database_2of2.zip Unzip and copy them to \tmp\databases NOTE: you might have to merge two unzipped folders to create a single folder. Create new groups and users Open a terminal and execute following commands. you might need root permission. groupadd -g 502 oinstall groupadd -g 503 dba groupadd -g 504 oper groupadd -g 505 asmadmin Now create the oracle user useradd -u 502 -g oinstall -G dba,asmadmin,oper -s /bin/bash -m oracle You will prompt to set to password. set a momorable password and write it down. (mine is orac

DBCA : No Protocol specified

when trying to execute dbca from linux terminal got this error message. now execute the command xhost, you probably receiving No protocol specified xhost:  unable to open display ":0" issue is your user is not allowed to access the x server. You can use xhost to limit access for X server for security reasons. probably you are logged in as oracle user. switch back to default user and execute xhost again. you should see something like SI:localuser:nuwan solution is adding the oracle to access control list xhost +SI:localuser:oracle now go back to oracle user and try dbca it should be working

Java Head Dump Vs Thread Dump

JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects. JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads. Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place.  Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser. Core dump is a os level memory usage of objects. It has more informaiton t