javapandit.net
  • Home
  • Quick Java
    • Exception Handling
    • Collections Framework
  • Java Best Practices
  • Web Services
    • Web Service Basics
    • Ten Basic webservice concepts
    • XML
    • Apache Axis
    • Restful Web Services
  • JMS Concepts
    • JMS- MySQL
  • Hadoop
    • NoSQL DATABASEs
    • Apache Sqoop
    • Hadoop Interview Questions
  • Java 5
  • Java 8
    • Java 8 : Lambda Expressions
  • JDBC
  • Java Architect
    • Enterprise application re-platforming strategies
    • Java Memory Management
  • Java Programs
  • Technical Tips
    • How to set JAVA_HOME environment variable
    • How to create an auto increment field in Oracle?
    • Linux Commands
  • Best Java Interview Questions
    • Java Interview Questions- YouTube
  • Interview Questions
    • Java Tech interview Questions
    • Core Java Interview Questions >
      • core tech questions1
      • Java Collection interview questions
      • Java Concurrency
    • Servlets Interview Questions
    • JSP Interview Questions
    • Java Web Services Interview Questions
    • EJB Interview Questions
    • XML Interview Questions
    • JMS Interview Questions
  • Struts Interview Questions
    • Struts 2 Interview Questions
  • Java EE Architects Interview Questions
    • Java Architect Interview Questions
    • Top 10 reasons for Java Enterprise Application Performance Problems
    • Web Application Scalability Questions for IT Architect
  • JavaPandit's Blog
  • Web Services Interview Questions
  • Servlets And JSP
  • Oracle SOA Interview Questions
    • Open ESB /JBI
    • BPEL Language
  • Log4J
  • Ant
  • Maven
  • JMeter
  • JUnit
  • Apache POI Framework
  • ORCALE SERVICE BUS (OSB) Interview Questions
  • J2EE Patterns
    • Model-View-Controller (MVC)
    • Front Controller
    • DAO
    • Business Delegate
    • Session Facade
    • Service Locator
    • Transfer Object
    • Design Patterns >
      • Creational Patterns >
        • Singleton
      • Behavioural Patterns
      • Structural Patterns
    • Intercepting Filter
  • SQL Interview Questions/Lab
  • Best Wall Papers
    • Devotional Songs
  • Java Community
  • HIBERNATE
  • ORACLE CC&B
    • Oracle CC&B Interview Questions
  • Docker
  • Little Princess
    • Sai Tanvi Naming Ceremony Celebrations
    • Rice Feeding Ceremony
    • Sai Tanvi Gallery
  • APPSC Career Guidance
    • AP History
    • Indian Polity
    • Indian Economy
    • Science & Technology
    • Mental Ability and Reasoning
    • Disaster Management
    • Current Affairs and Events
    • General Sciences >
      • Biology
      • Physics
      • Chemistry
    • Previous Question Papers
  • About Us
  • Contact US
Collections    
A collection allows a group of objects to be treated as a single unit. collection define a set of core Interfaces as follows.
 
                         Collection                                                 Map     Hash Map  class
                                                                                                     Hash Table   class     
                    
            Set    Hash set                      List    
                                                     Array List 
           Sorted set   Tree set          Vector List
                                                    Linked List                 Sorted map   Tree Map  class
Collection Interface :
  • The CI is the root of collection hierarchy and is used for common functionality across all collections.  There is no direct implementation of Collection Interface.

Set Interface: extends Collection Interface. The Class Hash set implements Set Interface.
  • Is used to represent the group of unique elements.
  • Set stores elements in an unordered way but does not contain duplicate elements.

Sorted set : extends Set Interface.  The class Tree Set implements Sorted set Interface.
  • It provides the extra functionality of keeping  the elements sorted.
  • It represents the collection consisting  of Unique, sorted elements in ascending order.

List : extends Collection Interface. The classes Array List, Vector List & Linked List  implements List Interface.
  • Represents the sequence of numbers in a fixed order.
  • But may contain duplicate elements.
  • Elements can be inserted or retrieved by their position in the List using Zero based index.
  • List stores elements in an ordered way.

Map Interface:basic Interface.The classesHash Map & Hash Table implements Map interface.
  • Used to represent the mapping of unique keys to values.
  • By using the key value we can retrive the values. Two basic operations are get( ) & put( ) .

Sorted Map : extends Map Interface.  The Class Tree Map implements Sorted Map Interface.
  • Maintain the values of key order.
  • The entries are maintained in ascending order.

Collection classes:
                          
HashSet : Implements Set Interface.                                   HashSet hs=new HashSet( );
  • The elements are not stored in sorted order.                          hs.add(“m”);

TreeSet : Implements Sorted set Interface.                           TreeSet ts=new TreeSet( );
  • The elements are stored in sorted ascending order.                ts.add(“H”);                                                
  • Access and retrieval times are quit fast, when storing a large amount of data.

Vector : Implements List Interface.
  • Vector implements dynamic array.                               Vector v = new vector( );
  • Vector is a growable object.                                   V1.addElement(new Integer(1));
  • Vector is Synchronized,  it can’t allow special characters and null values.
  • All vector starts with intial capacity, after it is reached next time if we want to store object in vector, the  vector automatically allocates space for that Object plus extra room for additional Objects.

ArrayList : Implements List Interface.

  • Array can dynamically increase or decrease size.               ArrayList a1=new ArrayList( );
  • Array List are ment for Random ascessing.                                    A1.add(“a”);
  • Array List are created with intial size, when the size is increased, the collection is automatically enlarged. When an Objects are removed, the array may be shrunk.

Linked List : Implements List Interface.
  • Inserting or removing elements in the middle of the array.   LinkedList l1=new LinkedList( );
  • Linked list are meant for Sequential accessing.                              L1.add(“R”);   
  • Stores Objects in a separate link.
 
 Map Classes:    Abstract Map; Hash Map ; Tree Map
Hash Map : Implements Map Interface. Hashmap() , Hashmap(Map m), Hashmap(int capacity)
  • The Elements may not in Order.
  • Hash Map is not synchronized and permits null values
  • Hash Map is not serialized.                                    Hashmap hm = new HashMap( );                
  • Hash Map supports Iterators.                               hm.put(“Hari”,new Double(11.9));

Hash Table : Implements Map Interface.
  • Hash Table is synchronized and does not permit null values.
  • Hash Table is Serialized.                                       Hashtable ht = new Hashtable( );                             
  • Stores key/value pairs in Hash Table.                  ht.put(“Prasadi”,new Double(74.6));
   A Hash Table stores information by using a mechanism called hashing. In hashing the informational content of a key is used to determine a unique value, called its Hash Code. The Hash Code is then used as the index at which the data associated with the key is stored. The Transformation of the key into its Hash Code is performed automatically- we never see the Hash Code. Also the code can’t directly index into h c.


Tree Map : Implements Sorted Set Interface.                     TreeMap tm=new TreeMap( );
  • The elements are stored in sorted ascending order.       tm.put( “Prasad”,new Double(74.6));    
  • Using key value we can retrieve the data.                            
  • Provides an efficient means of storing key/value pairs in sorted order and allows rapid retrivals.

Iterator: Each of collection class provided an iterator( ).
 By using this iterator Object, we can access each element in the collection – one at a time.
 We can remove() ;     Hashnext( ) – go next; if it returns false –end of list.
 
      Iterarator                                                               Enumerator
Iterator itr = a1.iterator( );                           Enumerator vEnum = v.element( );
While(itr.hashNext( ))                                           System.out.println(“Elements in Vector :”);
  {                                                              while(vEnum.hasMoreElements( ) )
    Object element = itr.next( );                        System.out.println(vEnum.nextElement( ) + “ “);
    System.out.println(element + “ “); 
  }

Collections
1.Introduction
2.Legacy Collections
       1. The Enumeration Interface
       2. Vector
       3. Stack
       4. Hashtable
       5. Properties
3.Java 2 Collections
       1. The Interfaces of the collections framework
       2. Classes in the collections framework
      3. ArrayList & HashSet
      4. TreeSet & Maps


Introduction   :
•Does your class need a way to easily search through thousands of items quickly?
• Does it need an ordered sequence of elements and the ability to rapidly insert and remove elements in the middle of the sequence?• Does it need an array like structure with random-access ability that can grow at run time?
 
 
              List                                            Map
                |                                                      |       
       Abstract List                                         Dictonary                |                                            |
           Vector                                      HashTable
                |                                            |                 
            Stack                                               Properities 
The Enumeration Interface :
 
•enumerate (obtain one at a time) the elements in a collection of objects.
specifies two methods :
boolean hasMoreElements()  :  Returns true when there are still more elements to extract, and false when all of the elements have been enumerated.
Object nextElement() :  Returns the next object in the enumeration as a generic Object reference.
 
    VECTOR  :
  • Vector implements dynamic array.                              Vector v = new vector( );
  • Vector is a growable object.                                 V1.addElement(new Integer(1));
  • Vector is Synchronized,  it can’t allow special characters and null values.
  • Vector is a variable-length array of object references.
  • Vectors are created with an initial size.
  • When this size is exceeded, the vector is automatically enlarged.
  • When objects are removed, the vector may be shrunk.
 
  Constructors :   Vector()  :  Default constructor with initial size 10.
Vector(int size)  :  Vector whose initial capacity is specified by size.
Vector(int size,int incr)  :Vector whose initialize capacity is specified by size and whose increment is specified by incr.
Methods  :
final void addElement(Object element) : The object specified by element is added to the vector.
final Object elementAt(int index) : Returns the element at the location specified by index.
final boolean removeElement(Object element) : Removes element from the vector
final boolean isEmpty() :  Returns true if the vector is empty, false otherwise.
final int size() : Returns the number of elements currently in the vector.
final boolean contains(Object element) : Returns true if element is contained by the vector and false if it is not. 
 
STACK :
•Stack is a subclass of Vector that implements a standard last-in, first-out stack
Constructor :  Stack()  Creates an empty stack.
 
Methods  :
Object push(Object item) : Pushes an item onto the top of this stack.
Object pop() :  Removes the object at the top of this stack and returns that object as the value of this function. An EmptyStackException is thrown if it is called on empty stack.
boolean empty()  :  Tests if this stack is empty.
Object peek()  :  Looks at the object at the top of this stack without removing it from the stack.
int search(Object o)  : Determine if an object exists on the stack and returns the  number of pops that would be required to bring it to the top of the stack.
 
 
    HashTable :
  • Hash Table is synchronized and does not permit null values.
  • Hash Table is Serialized.                                     Hashtable ht = new Hashtable( );                             
  • Stores key/value pairs in Hash Table.                 ht.put(“Prasadi”,new Double(74.6));
  • Hashtable is a concrete implementation of a Dictionary.
  • Dictionary is an abstract class that represents a key/value storage repository.
  • A Hashtable instance can be used store arbitrary objects which are indexed by any other arbitrary object.
  • A Hashtable stores information using a mechanism called hashing.
  • When using a Hashtable, you specify an object that is used as a key and the value (data) that you want linked to that key.
 
Constructors :      Hashtable()                     Hashtable(int size)
 
Methods  :
Object put(Object key,Object value) : Inserts a key and a value into the hashtable.
Object get(Object key) : Returns the object that contains the value associated with key.
boolean contains(Object value) : Returns true if the given value is available in the hashtable. If not, returns false.
boolean containsKey(Object key) : Returns true if the given key is available in the hashtable. If not, returns false.
Enumeration elements() : Returns an enumeration of the values contained in the hashtable.
int size() : Returns the number of entries in the hashtable.
 
 
Properties
•Properties is a subclass of Hashtable
• Used to maintain lists of values in which the key is a String and the value is also a String
• Constructors
Properties()
Properties(Properties propDefault) : Creates an object that uses propDefault for its default value.
Methods  :
String getProperty(String key) : Returns the value associated with key.
 
Strng getProperty(String key, String defaultProperty) : Returns the value associated with key. defaultProperty is returned if key is neither in the list nor in the default property list .
Enumeration propertyNames() : Returns an enumeration of the keys. This includes those keys found in the default property list. 

The Interfaces in Collections Framework 
  Collection                    Map                    Iterator
Set         
List                                 SortedMap           ListIterator
                        |
                   SortedSet
 
Collection :
  • A collection allows a group of objects to be treated as a single unit.
  • The Java collections library forms a framework for collection classes.
  • The CI is the root of collection hierarchy and is used for common functionality across all collections.
  • There is no direct implementation of Collection Interface.
  • Two fundamental interfaces for containers:
     • Collection
boolean add(Object element) : Inserts element into a collection
 
Set Interface: extends Collection Interface.   The Class Hash set implements Set Interface.
  • Is used to represent the group of unique elements.
  • Set stores elements in an unordered way but does not contain duplicate elements.
  • identical to Collection interface, but doesn’t accept duplicates.
 
Sorted set : extends Set Interface.  The class Tree Set implements Sorted set Interface.
  • It provides the extra functionality of keeping  the elements sorted.
  • It represents the collection consisting  of Unique, sorted elements in ascending order.
  • expose the comparison object for sorting. 
 
List Interface :
  • ordered collection – Elements are added into a particular position.
  • Represents the sequence of numbers in a fixed order.
  • But may contain duplicate elements.
  • Elements can be inserted or retrieved by their position in the List using Zero based index.
  • List stores elements in an ordered way.
 
Map Interface: Basic Interface.The classes Hash Map & HashTable implements Map interface.
  • Used to represent the mapping of unique keys to values.
  • By using the key value we can retrive the values.
  • Two basic operations are get( ) & put( ) .
 
boolean put(Object key, Object value)  :  Inserts given value into map with key
Object get(Object key) :  Reads value for the given key.
 
Tree Map Class: Implements Sorted Map Interface.                
  • The elements are stored in sorted ascending order.         
  • Using key value we can retrieve the data.                            
  • Provides an efficient means of storing key/value pairs in sorted order and allows rapid retrivals.
      TreeMap tm=new TreeMap( );
      tm.put( “Prasad”,new Double(74.6));
The Classes in Collections Framework
                          Abstract Collection

 
 

       Abstract List                              Abstract Set                              Abstract Map

 
 

  Abstract       Array List         Hash Set          Tree Set           Hash Map          Tree Map
Sequential    
   List


Linked List 
ArrayList
• Similar to Vector: it encapsulates a dynamically reallocated Object[] array
• Why use an ArrayList instead of a Vector?
• All methods of the Vector class are synchronized, It is safe to access a Vector object from two threads.
• ArrayList methods are not synchronized, use ArrayList in case of no synchronization
• Use get and set methods instead of elementAt and setElementAt methods of vector
 
HashSet
• Implements a set based on a hashtable
• The default constructor constructs a hashtable with 101 buckets and a load factor of 0.75
HashSet(int initialCapacity)
HashSet(int initialCapacity,float loadFactor)
loadFactor is a measure of how full the hashtable is allowed to get before its capacity is automatically increased
• Use Hashset if you don’t care about the ordering of the elements in the collection
 
 
TreeSet
• Similar to hash set, with one added improvement
• A tree set is a sorted collection
• Insert elements into the collection in any order, when it is iterated, the values are automatically presented in sorted order
 
• Maps :  Two implementations for maps:
HashMap:
  • hashes the keys
  • The Elements may not in Order.
  • Hash Map is not synchronized and permits null values
  • Hash Map is not serialized.                                                                                    
  • Hash Map supports Iterators. 
 
TreeMap
• uses a total ordering on the keys to organize them in a search tree
• The hash or comparison function is applied only to the keys
• The values associated with the keys are not hashed or compared.

Picture
Powered by Create your own unique website with customizable templates.