Search This Blog

Monday 6 March 2017

The List Interface

The List Interface


List is an ordered Collection, sometimes called a sequence. Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for the following:
·         Positional access — manipulates elements based on their numerical position in the list. This includes methods such as get, set, add, addAll, and remove.
·         Search — searches for a specified object in the list and returns its numerical position. Search methods include indexOf and lastIndexOf.
·         Iteration — extends Iterator behaviour to take advantage of the list's sequential nature. The listIterator methods provide this behavior.
·         Range-view — The sublist method performs arbitrary range operations on the list.

The Java platform contains two general- purpose List implementations.
·         ArrayList, which is usually the better-performing implementation
·         LinkedList which offers better performance under certain circumstances.

ArrayList
LinkedList
ArrayList internally uses dynamic array to store the elements.
LinkedList internally uses doubly linked list to store the elements.
Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.
ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.

Important methods of List Interface
Method
Description
Boolean add(Object obj)
Appends the specified element to the end of this list
void add(int index, Object obj)
Inserts the specified element at the specified position in this list
boolean addAll(int index, Collection c)
Inserts all elements of c into the invoking list at the index passed in the index. Returns true if the invoking list changes and returns false otherwise.
Object get(int index)
Returns the object stored at the specified index within the invoking collection.
int indexOf(Object obj)
Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
int lastIndexOf(Object obj)
Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.
ListIterator listIterator( )
Returns an iterator to the start of the invoking list.
ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.
Object remove(int index)
Removes the element at position index from the invoking list and returns the deleted element.
Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list.
List subList(int start, int end)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.


Sunday 5 March 2017

The Set Interface

The Set Interface
A Set is a Collection that cannot contain duplicate elements. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are not added. 
The Java Platform contain three general purpose implementations of Set
·        HashSet 
·        TreeSet
·        LinkedHashSet

HashSet stores its elements in a hash table, and performance wise it is the best implementation. It makes no guarantees concerning the order of iteration.

TreeSet stores its elements in a tree structure, and the elements are orders based on their values. Its performance is slower than HashSet. 

LinkedHashSet is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the Set. 

Set Interface Basic Operations

·        The add() method adds the specified element to the Set if it is not already present.
·        The remove() method removes the specified element from the Set if it is present.
·        The size() operation returns the number of elements in the Set. The isEmpty() method is used to check if this set contains no elements
·        The iterator() method returns an Iterator over the Set.

Set Interface Bulk Operations

Bulk operations are particularly well suited to Sets; when applied, they perform standard set-algebraic operations. Suppose s1 and s2 are sets. Here's what bulk operations do:
  • s1.containsAll(s2) — returns true if s2 is a subset of s1.
  • s1.addAll(s2) — transforms s1 into the union of s1 and s2.
  • s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2.
  • s1.removeAll(s2) — transforms s1 into the set difference of s1 and s2.
Example of Set using HashSet and SortedSet

import java.util.*;
public class SetDemo {

  public static void main(String args[]) {
      int numbers[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
            set.add(numbers[i]);
         }
        
         System.out.println("Natural Set : ");
         System.out.println(set);

         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("Sorted Set : ");
         System.out.println(sortedSet);
      }
      catch(Exception e) {}
   }
}

Thursday 2 March 2017

Collection Interfaces

Collection Interfaces
The core collection interfaces encapsulate different types of collections. These interfaces allow collections to be manipulated independently of the details of their representation. Core collection interfaces are the foundation of the Java Collections Framework.

The following describes the core collection interfaces:
  • Collection — Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. Some types of collections allow duplicate elements, and others do not. Some are ordered and others are unordered. The Java platform provides implementation of more specific sub interfaces like Set and List and doesn't provide any direct implementations of Collection interface.
  • Set — Set is a collection that cannot contain duplicate elements.
  • List — List is an ordered collection. Lists can contain duplicate elements.
  • Queue — Queue is a collection used to hold multiple elements prior to processing.
  • Deque — Deque is a collection used to hold multiple elements prior to processing. In a deque all new elements can be inserted, retrieved and removed at both ends.
  • Map — Map is an object that maps keys to values. A Map cannot contain duplicate keys; each key can map to at most one value.
  • SortedSet — SortedSet is a Set that maintains its elements in ascending order.
  • SortedMap — SortedMap is a Map that maintains its mappings in ascending key order.
The Collection interface contains methods that perform basic operations, such as 
·        int size()
·        boolean isEmpty()
·        boolean contains(Object element)
·        boolean add(E element)
·        boolean remove(Object element)
·        Iterator<E> iterator()

It also contains methods that operate on entire collections
·        boolean containsAll(Collection<?> c)
·        boolean addAll(Collection<? extends E> c)
·        boolean removeAll(Collection<?> c)
·        boolean retainAll(Collection<?> c)
·        void clear().
Traversing Collections
There are three ways to traverse collections
1.     using aggregate operations
2.     using the for-each construct
3.     using Iterators

Aggregate Operations
In JDK 8 and later, the preferred method of iterating over a collection is to obtain a stream and perform aggregate operations on it.
Aggregate operations are often used in conjunction with lambda expressions to make programming more expressive, using less lines of code.
The following code sequentially iterates through a collection of Employees and prints out the Name of Employee of HR department
myEmployeeCollection.stream()
.filter(e -> e.getDepartment() == “HR”)
.forEach(e -> System.out.println(e.getName()));

for-each Construct
The for-each construct allows you to concisely traverse a collection or array using a for loop.
The following code uses the for-each construct to print out each element of a collection on a separate line.
for (Object o : collection)
    System.out.println(o);
           
Iterators
An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively.
You get an Iterator for a collection by calling its iterator method. The following is the Iterator interface.
public interface Iterator<E> {
    boolean hasNext();
    E next();
    void remove(); //optional
}
The hasNext method returns true if the iteration has more elements, and the next method returns the next element in the iteration.

The remove method removes the last element that was returned by next from the underlying Collection. 

Collection Interfaces
Collection Interfaces

Wednesday 1 March 2017

Collections in Java

Collections in Java


A collection is an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:
  • Interfaces: Interfaces allow collections to be manipulated independently of the details of their representation.
  • Implementations: These are the concrete implementations of the collection interfaces. They represent reusable data structures.
  • Algorithms: Are the methods that perform useful operations, for example searching and sorting, on objects that implement collection interfaces. The algorithms are polymorphic: that is, the same method can be used on many different implementations the collection interface.

Benefits of the Java Collections Framework


  • Reduces programming effort
  • Increases program speed and quality
  • Interoperability among unrelated APIs.
  • Reduces effort to learn and to use new APIs
  • Reduces effort to design new APIs
  • Increases software reuse