You are on page 1of 7

List Vector Hashtable Enumeration interface abstract string file streams inheritance class constructor data hiding Array

ArrayList - binarySearch() method uses a binary search to find a specified value, this met hod must be appliced to sorted arrays - ClassCastException if array contains elements that can not be compared(ex Doub le and StringBuffer) - copyOf() to copy an array(ex static char[] copyOf(char [] source, int len)) - original array is specified by source and length of the copy is specif ied by len - if "len" is negative then NegativeArraySizeException - if "source" is null, then NullPointerException returned - if target is not matching with source then "ArrayStoreException" - copyOfRange() -> returns a copy of a range within an array(ex static int[] cop yOfRange(int[] source,int start,int end) - The range to copy is specified by the indices passed via start and end - The range runs from start to end-1 - if the range is longer than source, then the copy is padded with zeros (for int),nulls(for object),false(boolean arrays) - start is negative or greater than the length of source, an "ArrayIndex OutOfBoundsException" thrown - if start is greater than end, an "IllegalArgumentException" is throws - equals() --> compares and return "true"if both array are same,otherwise "false " ex:- static boolean equals(int array1[],int array2[]) - deepEquals() - compare 2 arrays and its nested array , returns "ture" or "fals e" - ex:- static boolean deepEquals(Object[] a,Object[] b) - fill() - to fill the values to all elements in an array, it has 2 versions, on e will fill all elements and another one will fill the subset of the array ex:- static void fill(char array[] ,char value) ex:- static void fill(char array[],int start,int end, char value) - sort() - to sort array - ex:- static void sort(int array[]) - static void sory(int array[],int start, int end) - to String(), hascode(),deepToString(),deepHashCode() methods also provided by Arrays ============================================================== COLLECTIONS:- Collection Framework standardizes the way in which groups of objects a re handled by the programs - Algorithms are another important part of the collection mechanism

- Algorithms operates on collections and are defined as static methods w ithin the Collections class - Another item closely associated with the Collections Framework is the Iterator Interface - An iterator provides a means of Enumerating the contents of a collecti on. - Because each collections provides an iterator, the elements of any col lection class can be accessed through the methods defined by Iterator - Collection Framwork defines serveral map interfaces and classes(Maps s tore key/value Pairs) - In JDK 5,the fundamental changes were made to the Collections Framewor k,the changes included addition of Generics,autoboxing/unboxing, and "for-each " style for loop ==================Generics Fundamentally Changed the Collections Framework ====================== - The Entire Coolections Framework was reengineered for it - All Collections are no Generic, and many of the methods that operate o n collections take generic type parameters. - Generics added the one featurethat collections had been missing which is "Type Safety".Prior to Generics, all Collections stored "Object" references, which mean collections could store any type of object. - With Generics, it is possible to explicitly state the type of data bei ng stored, and run-time type mismatch errors can be avoided by doing so *************************************IMPORTANT********************************** ********************** - To gain the advantages that generic bring collections, the older code will need to be rewritten. - This is also imporatant because pre-generics code will generate warnin g messages when compiled by a moden java compiler, To eliminate these warning, you will need to add type information to all your collection code ******************************************************************************** ******************** Auto boxing Facilitates the Useeee of Primitive Types:Auto boxing Facilitates storing Primitive types in Collections. As you will see, collection will store only reference type, not primitive values.In the past, if you wanted to store a primitive values, such as an int , in a collecti on, you had to manually box it into its type wrapper. When the value was retriev ed, it needed to be manually unboxed(by using an explicit cast) into its proper primitive type. Because of autoboxing/unboxing, Java can automatically perform t he proper boxing and unboxing needed when storing or retrieving primitive types. There is no need to manually perform these operations. ========================The "For-Each" Style "for" Loop ================== All Collection classes in the Collection Framework were retrofitted to implement the Iterable interface, which means that a collection can be cycled through by use of the "for-each" style "for" loop.In the past, cycling through a collection required the use of an iterator, with the programmer manually constructing the loop. Although iterators are still needed for some uses, in many cases, iterator-based loops can be replaced by "for" loops ================================================================= COLLECTION INTERFACES:The below are the some of the collection interfaces...... Collection -> Enables you to work with groups of objects, it is at the top of th e collections hierarchy. -In Addition to the collections interfaces, collections also use the "Co mparator", "RandomAccess" "Iterator", "ListIterator" interfaces

-Comparator -->defines how two objects are compared -Iterator,ListIterator -->enumerate the objects within a collection. -RandomAccess --->a list indicates that it supports efficient,random acc ess to its elements To proved the greatest flexibility , the "collection interfaces" allow some meth ods to be optional. The optional methods enable you to modify the contents of a collection.Collections that support these methods are called modifiable.Collecti ons that do not allow their contents to be changed are called unmodifiable. If a n attempt is made to use one of these methods on an unmodifiable collection, an "UnsupportedOperationException" is thrown. All the built-in collections are modi fiable. The Collection Interface:The Collection interface is the foundation upon which the Collection Fra mwork is built because it must be implemented by any class that defines a collec tion. Collection is a generic interface that has this declaration: interface Collection<E> Here , E Is object type that the collections will hold. "Collection" extends the "Iterable" interface.This means that all collections can be cycled through by u se of the "for-each" style for loop.(Recall, that tonly classes implement "Itera ble" can be cycled through by the for) - Collection declares the core methods that all collections will have. - Several of these methods can throw an "UnsupportedOperationException" if a collection can not be modified - ClassCaseException is generated when one object is incompatible with a nother, such as when an attempt is made to add an incompatible object to a collection - Illegal ArgumentException is thrown if an invalid argument is used - IllegalStateException is thrown if an attempt is made to add an elemen t to fixed-length collection that is full to add object in collection ------------------------------------------------->ad d() to add all object from one collection to another -------------------------->addA ll() to remove an object in collection -----------------------------------------> rem ove() to remove a group of object --------------------------------------------->remov eAll() to remove all elements except those of a specified group by calling ----->retain All() to empty a collection , cal ------------------------------------------------>cle ar() to check the specific object calling ----------------------------------------> c ontains() to determine whether one collection contains all the members of another --->cont ainsAll() to check whether a collection is empty bycalling ------------------------------> isEmpty() to check the number of elements in a collection -------------------------------> size() to return an iterator to a collection ------------------------------------------ iterator() to return an array that contains the ements stored in the invoking collection --toArray() [the first retuns an array of Object, then retuns an array of element s that have the same ty pe as the array specified as parameter] =============================================================================== The List Interface:-

syntax:inteface List<E> "E" is the type of Object that will hold in it - "List" interface extends "Collection" - List declares the behaviour of a collection that stores a sequence of elements. - Elements can be inserted or accessed by their position in the list usi ng a Zero-based index. - List may contain duplicate values - In Addition to the methods defined by Collection, List has its own met hods - "UnSupportedOperationException" if the list can not modified - "ClassCastException" -incompatible object to list - "IndexOutOfBoundsException" - if invalid index is used - "NullPointerException" - if null object is trying to store in a list - "IllegalArgumentException" - if an invalid argument is used - null elements are not allowed in List methods defined by "List" - add(int,E) -addAll(int,Collection) -get(int index) ---> to get the object at given index location - set(int index, E obj) to set the value to the element - indexOf(Object obj) - returns the index of the first instance of obj i n the invoking list.if obj is not an element of the list, -1 is returned - lastIndexOf(Object obj) - returns the index of the last instance of o bj in the invoking list. if obj is not an element of the list, -1 is returned - subList(int start, int end) - returns a list that includes elements fr om start to end-1 in the invoking list. Elements in the returned list are also r eferenced by the invoking object =========================================================================== Set Interface :- defines a set - extends Collection - declare the behavior of a collection that does not allow duplicate ele ments, Therefore the add() method returns "false" if an attempt is made to add d uplicate elements to a set. It doesnt define any additional methods of its own. Syntax:interface Set<E> ===================================================================== SortedSet Interface:interface SortedSet<E> E ---> Specify the type of objects that the set will hold - extends "Set" - declare the behavior of a set sorted in ascending order - in addition to methods defined by "Set", SortedSet also defines its ow n methods - to obtain fist and last of the set, use first(), last() methods - to get the subset of the sorted set use subSet() - "NoSuchElementException" - if there is no items are contained in the i nvoking set - "ClassCastException" ,"NullPointerException" ,"IllegalArgumentExceptio n" are also thrown ====================================================================== NavigableSet Interface:-

Syntax:= interface NavigableSet<E> E ---> Specify the type of objects that the set will hold. - Extends SortedSet - declare the behavior of a collection that supports the retrieval of el ements based on the closest match to a given value or values. - In Addition to methods that was inherited from SortedSet, NavigableSet also adds lot of its own methods - ClassCastException, NullPointerException, IllegalArgumentException are sometime thrown based on the conditions ================================== Queue Interface Syntax:interface Queue<E> - extends Collection - declare the behavior of a queue which is often a first-in,first-out li st. -"ClassCastException" - when the object is incompatible with the element s in the queue - "NullPointerException" - if an attempt is made to store a null object and null elements are not allowed in the queue - "IllegalArgumentException" is thrown if an invalid argument is used - "IllegalStateException" - if an attempt is made to add an element to f ixed-lenth queue that is full - "NoSuchElementException" - if an attempt is made to remove an element from an empty queue Methods defined by Queue interface:- Elements can only be removed from the head of the queue, poll(), and r emove() are used to remove elements - poll() method returns null if the ques is empty when you remove - remove() throws an exception if the queue is empty - peek() returns the element at the head of the queue. it returns null i f the queue is empty, the element is not removed - element() returns the element at the head of the queue. The element is not removed, it throws NOSuchElementException if the queue is empty == =============================================================== Deque Interface:Syntax :interface Deque <E> E ---> Specify the type of objects that the deque will hold. - extends Queue - declares the behavior of a double-ended queue - double-ended queues can function as standard, first-in, first-ou queue s or as last-in,first-out stack. - ClassCastException,NullPointerException,IllegalArgumentException,Illeg alStateException,NoSuchElementException are thrown ..... Methods in Deque... - pop() - returns the element at the head of the deque, removing it in t he process. it throws NoSuchElementException if the deque is empty - push() - adds obj to the head of the deque. throws an IllegalStateExce ption if a capacity-restricted deque is out of space - pop() and push() methods enables a Deque to function as a stack, Also

notice the descendingIterator() method. It returns an iterator that returns elem ents in reverse order. In otehr words, it returns an iterator that moves from et he end of the collection to the start. A Deque implementation can be "capacity r estrcited" wchich means that only a limited number of elements can be added to d eque.when this is the case , an attempt to add an element to the deque can fail. Deque allows you to handle such a failure in two ways, one is addFirst() and ad dLast() throws an IllegalStateException if a capacity-restricted deque is full. Second is offerFirst() and offerLast() returns false if the element can not be a dded .... ============================================================================== COLLECTION Classes:Class:AbstractCollection ----> implements most of the Collection interface AbstrctList ------> Extends AbstractCollection and implements most of the Li st interface AbstrctQueue -------> Extends AbstractCollection and implements parts of the Queue interface AbstractSequentialList------> Extens AbstractList for use by a collection that u ses sequential rather than random access of its elements, LinkedList -------> implements a linked list by extending AbstractSequenti alList ArrayList -------> implements a dynamic array by extending Abstrac tList ArrayDeque --------> implements a dynamic double-ended queue by extending A bstractCollection and implementing the Deque interface AbstractSet -------> Extends AbstractCollection and implements most of the S et Interfaces EnumSet -------> Extends AbstractSet for use with enum elements HashSet ------>Extends AbstractSet for use with a hash table LinkedHashSet ------> Extends HashSet to allow insertion-order iterations PriorityQueue ----->Extends AbstractQueue to support a priority-based queue TreeSet ----->implements a set stored in a tree, extends AbstractSet ==================================== The ArrayList Class:- it is dynamic array - stores variable-length array of object references - it can dynamically increase or decrease in size - Array Lists are created with initial size - when this size is exceeded , the collection is automatically enlarged. , when objects are removed, the array can be shrunk - ArrayList has constructors (ArrayList(),ArrayList(Collection<? extends E> C), ArrayList(int capacity)) - First ArrayList() --> builds an empty array list - Second ArrayList(Collection <? extends E> c) ----> builds an array lis t that is initialized with the elements of the "collection c" - Third ArrayList(int capacity) --->builds an array list that has the sp ecified initial capacity - We can manually increase the size of the ArrayList using ensureCapacit y(int capacity) method - to reduce the space in ArrayList, you can use trimToSizt() method Obtaining an Array From an ArrayList:- we can do by calling toArray(), which is defined by Collection, we may need to get the array sometime for the following reason - To obtain faster processing times for certain operations - To Pass an array to a method that is not overloaded to accept a collection

- To integrate colleciton-based code with legacy code that does not understand collections - First it returns an array of Object, then it returns the elemtns of an array ================================================================================ === The LinkedList Class:- extends "AbstractSequentialList" and implements "List",De que, Queue Interfaces Syntax:- class LinkedList<E> - it has 2 constructor ========= Hashtable it is integrated in Collection Framework it was reengineered to also implement the Map Interface like HashMap, Hashtable stores key/value pairs in a hash table Hash table can store the object that override the hashCode() and equals( ) methods that are defined by Object hascode() method must compute and return the hash code for the object. Of Course, equals() compares two objects many java classes already implement the hashCode() method String implements both hashCode() and equesl()

You might also like