Saturday, August 6, 2016

JAVA Collections Framework


The Collections Framework is a set of interfaces and classes that allow the user to store a lot of data in a single object similar to the way an array stores data but without a lot of their limitations.

For example, once the size of an array is setup it cannot be changed without creating a whole new array. There are also not very many built-in methods to act on arrays and you have to precisely control the location of each data component in the array.

A Collection is similar to an array and contains data of a certain type but with some added benefits:

Benefits:

- Can grow or shrink in size automatically as needed
- Provides several standard data structures
- Choices on implementation for faster run-times
- Uses Code -to - Interface principles





Collection Interfaces


Collection Interfaces define a set of built-in methods that may be implemented on the collection elements, and there are several types:

Collection Framework Interfaces:


- Collection: most basic and generic interface, contains a collection of objects
- Set: cannot take any duplicate elements
- SortedSet: ordered version of the Set interface
- List: ordered collection that allows duplicates, retrieval based on integer index location
- Queue: follows a "first in - first out" principle
- Map: supports multiple data types in key pairs, does not allow duplicates
- SortedMap: maintains its keys in ascending order



The basic hierarchy of Collection Interfaces looks like:



Collection Classes


Where Collection Interfaces define the available built-in methods that will work with different types of collections, Collection Classes actually implement the methods being called. The Collection Class also defines more clearly exactly how the elements in a collection are stored.



Types of Collection Classes:


- ArrayList: a resizable array, automatically creates a new array and copies all data in the original array when needed

Positives: Retrieving data is very fast due to being able to use the array index location integer to find the specific element needed, memory is minimal only needing the element values

Negatives: Re-sizing the array can be slow if a large number of elements exist due to having to create a copy of the original array



- LinkedList: stores each element in a separate package/node that is linked to other separate nodes

Positives: Re-sizing is fast because individual nodes can be easily added or removed

Negatives: Retrieval can be slow because the whole list must be gone through from the beginning until the data node needed is found, memory is less efficient and needs to know the element value and its links/relationships to other nodes



- HashSet / HashMap: stores elements randomly in a table format using a key generated by the "hash function"

Positives: Retrieval is fast due to quick key-lookup via the hash function

Negatives: Processing elements is not done in order since the table stores elements randomly




- TreeSet / TreeMap: stores elements in a tree formation with parent - child links

Positives: Allows for processing the elements in sorted order

Negatives: Retrieval is slower due to having to walk through the whole tree to get to the element of interest


The table below shows the possible Collection Classes that can be used for each type of Collection Interface.








Initializing a Collection


You must use the util package in JAVA to use collections:


import java.util.*;


A Collection is a generic type (class or interface that allows the specific type of data to be changed at a later time), and is initialized by using <>

The basic format of a collection initialization looks like:

Collection <Type> name = new Collection_Class <Type> ();


It is good practice to use the most basic interface callouts of Set, List, Map, etc. for the first Collection Type callout. This makes it easy to change the implementation easily later.


For example, an ArrayList Collection initialization may look like this:



List<String> inputText = new ArrayList <String> ();


Using Methods on a Collection

Since the interface defines the methods that may be used, let's look at the methods that are available in the most basic Collection Interface in the hierarchy.

Methods Available in the Collection Interface:

- add new elements  (add)
- remove elements  (remove)
- clear all collection (clear)
- search (contains)
- get size of collection (size)
- check to see if the collection is empty (isEmpty)
- return an iterator over the elements in the collection (iterator)



For example, you can use the add method to add string data to the inputText collection we created:



string name1="Roger";
string name2 = "Philip";

List<String> inputText = new ArrayList <String> ();

inputText.add(name1);
inputText.add(name2);


The Set and SortedSet Interfaces contain the same available methods as the Collection Interface, but the List Interface adds some additional built-in methods:


Methods Available in the List Interface:

- add an element at a specific index location - add (int index, E element)
- remove an element at a specific index location - remove (int index)
- re-assign the value of a specific index location - set (int index, E element)
- get the current value of a specific index location - get (int index)
- search for the first index number of an object - indexOf (Object o) - search for the last index number of an object- lastIndexOf (Object o)
- return an iterator that can move forwards or backwards - listIterator()
The index locations starts with 0 and increases by integers of +1

Adding or removing elements using the list interface shift all other elements down (if adding) or up (if removing).


The Map Interface allows data to be input using a custom indexing system - instead of using the standard index locations starting with 0. This is done by assigning a key to each data element in the collection.

Interface Map <Key, Value>

Like the List Interface, the Map Interface provides additional built-in methods:


Methods Available in the Map Interface:

- add a (key, value) pair - put (K key, V value)
- looks up the value of a specified key - get (Object key)
- return a set of all keys - keyset ()
- return a set of all values - values ()





Iterating Over a Collection


Using Indexing


One way you can iterate over a collection is by using the familiar array indexing location with a for loop, similar to the way arrays are processed. Only collection types using the List interface use indexing.

For example, the previous ArrayList Collection of names that was created can be processed like this:


List<String> inputText = new ArrayList <String> ();

inputText.add("Roger");
inputText.add("Philip");

for(int i=0; i<inputText.size; i++) {
out.println(inputText.get(i));
}


Using For-Each Loop


The for - each loop as with arrays can be a good way to process through a collection with less code - but just as with arrays you cannot modify the collection data using this loop and all other limitations of the for - each loop apply.

The for - each loop for the example looks like this:


List<String> inputText = new ArrayList <String> ();

inputText.add("Roger");
inputText.add("Philip");

for(String inputName: inputText){
out.println(inputName);
}


Using Iterator


Collections can also be processed using the built-in iterator, which has three methods:

Iterator Methods:

- checks to see if there is a next element - hasNext()
- returns the next element - next()
- removes the last value that was returned by next - remove()


Processing the example with the iterator looks like:

List<String> inputText = new ArrayList <String> ();

inputText.add("Roger");
inputText.add("Philip");

Iterator<String> it_Text =inputText.iterator();

while( it_Text.hasNext() ) {
String inputName = it_Text.next();
out.println(inputName);
}

Iterators are a preferred way to process collections, since they work with all types of collections except the map interfaces and they work in a generic way.

The map interface contains the return methods that can be used in place of an iterator. The next two sections will take a closer look at ArrayList and HashMap Collections.

No comments:

Post a Comment