Collections 2

30
1 http://www.learn-java-tutorial.com/Java-Collections.cfm Collections The Java Collections API is a set of classes and interfaces designed to store multiple objects There are a variety of classes that store objects in different ways Lists store objects in a specific order Sets reject duplicates of any objects already in the collection Maps store objects in association with a key, which is later used to look up and retrieve the object (note that if an item with a duplicate key is put into a map, the new item will replace the old item) The basic distinctions are defined in several interfaces in the java.util package Collection is the most basic generally useful interface that most, but not all, collection classes implement o it specifies a number of useful methods, such as those to add and remove elements, ascertain the size of the collection, determine if a specific object is contained in the collection, or return an Iterator that can be used to loop through all elements of the collection (more on this later) o methods include: add(Object o), remove(Object o), contains(Object o), iterator() o note that removing an element removes an object that compares as equal to a specified object, rather than by position o Collection extends the Iterable interface, which only requires one method, which supplies an object used to iterate through the collection the List interface adds the ability to insert and delete at a specified index within the collection, or retrieve from a specific position the Set interface expects that implementing classes will modify the adding methods to prevent duplicates, and also that any constructors will prevent duplicates (the add method returns a boolean that states whether the operation succeeded or not; i.e., if the object could be added because it was not already there) o sets do not support any indexed retrieval the Map interface does not extend Collection, because its adding, removing, and retrieving methods use a key value to identify an element o methods include: get(Object key), put(Object key, Object value), remove(Object key), containsKey(Object key), containsValue(Object value), keySet(), entrySet()

description

coll

Transcript of Collections 2

1http://www.learn-java-tutorial.com/Java-Collections.cfmCollectionsThe Java Collections API is a set of classes and interfaces designed to store multiple objectsThere are a variety of classes that store objects in different ways Lists store objects in a specific order Sets reject duplicates of any objects already in the collection Maps store objects in association with a key which is later used to look up and retrieve the object !note that if an item with a duplicate key is put into a map the new item will replace the old item"The basic distinctions are defined in several interfaces in the java.util package Collection is the most basic generally useful interface that most but not all collection classes implement o it specifies a number of useful methods such as those to add and remove elements ascertain the si#e of the collection determine if a specific object is contained in the collection or return an $terator that can be used to loop through all elements of the collection !more on this later"o methods include: add!%bject o" remove!%bject o" contains!%bject o" iterator!" o note that removing an element removes an object that compares as e&ual to a specified object rather than by positiono Collection e'tends the $terable interface which only re&uires one method which supplies an object used to iterate through the collection the List interface adds the ability to insert and delete at a specified inde' within the collection or retrieve from a specific position the Set interface e'pects that implementing classes will modify the adding methods to prevent duplicates and also that any constructors will prevent duplicates !the addmethod returns a boolean that states whether the operation succeeded or not( i.e. ifthe object could be added because it was not already there" o sets do not support any inde'ed retrieval the Map interface does not e'tend Collection because its adding removing and retrieving methods use a key value to identify an element 2o methods include: get!%bject key" put!%bject key %bject value" remove!%bject key" contains)ey!%bject key" contains*alue!%bject value" key+et!" entry+et!" o maps do not support any inde'ed retrieval$n addition to the ,ist +et and -ap categories there are also several inferences you can make from some of the collection class names: a name beginning with Hash uses a hashing and mapping strategy internally although the key values usually have no meaning !the hashing approach attempts to provide an efficient and appro'imately e&ual lookup time for any element" a name beginning with Linked uses a linking strategy to preserve the order of insertion and is optimi#ed for insertion/deletion as opposed to appending or iterating a name beginning with Tree uses a binary tree to impose an ordering scheme - either the natural order of the elements !as specified by the Comparable interface implemented by many classes including +tring and the numeric wrapper classes" or an order dictated by a special helper class object !a Comparator" +everal additional interfaces are used to define useful helper classes: Enumeration provides a pair of methods that enable you to loop through a collection in a standardi#ed manner regardless of the type of collection !you test if there are more elements and if so retrieve the ne't element" o this interface is less fre&uently used now that the following interface has beenadded to the ./$o but many of the elements in J011 !servlets in particular" predate the $teratorconcept and were specified to use enumerations so they will still appear in new code Iterator is an improved version that allows an object to be removed from the collection through the iteratorThe following diagrams show some of the classes and interfaces that are available345Examples of CollectionsCollection Classes and InterfacesClassImplements or Extends Collection InterfaceInterface orCollectionSynchronisedNotesAbstractCollection abstract classan interface to act as skeleton to build most classesthat implement the Collection, interface.java.lang.reflect.ArrayClassReflection classes used to dynamically create Array objects where you dont know anything about them at compile time. You probably were looking for Arrays instead.java.sl.Array interfaceA class for storing and retrieving arrays in an !"# $!tandard "uery #anguage% database. You probably were looking for Arrays instead.Array#ist ClassA non&thread&safe #ist that is marginally faster than thread&safe 'ector. (n versions prior to )ava version *.+, the difference was more pronounced , - to + times faster. Rolling your own non&Collection array is about + times faster than 'ector. (n earlier non&optimising )'.s, the difference was more like +/ times faster. 0he mainoverhead of using Array#ist and 'ector is the casting needed to fish out the elements. Array#ist is like a 12 array that automatically grows. #ookup by dense ints. Considerably faster than a 3ash.ap.Arrays Classstatic methods for sorting and searching ordinary arrays, e.g. binary!earch, fill, sort. as#ist converts an array into a #ist Collection you can then feed tomethods e4pecting a Collection or #ist. 5ont confuse this with the two Array classes.Collection interface 0he interface that all collections implement that guarantee you can always add, remove, clear, si6e, iterator, contains, toArray etc. in a standard way. 5ont confuse this with the Collections class. toArray can be made smarter if you pass it an empty array to fill just the right si6e. 0hen you have an array of specific classes, not just generic 7bjects. 8se it like this9 Dogs[] dogs =6Collection Classes and InterfacesClassImplements or Extends Collection InterfaceInterface orCollectionSynchronisedNotes( Dogs [] )dogArrayList.toArray( new Dogs [dogArrayList.size()] );0he Collection. to!tring method implemented by all Collections is a great debugging tool to dump out the entire contents of a Collection in a reasonably human&readable format enclosing each element in 12.Collections Classstatic methods for operating on collections, e.g. sort, binary!earch, min, ma4, shuffle. 5ont confuse the Collections class with the Collection interface.java4.swing.tree.5efault0ree.odelClass0his was written to support !wings )0ree, but it will suffice as a generic tree collection.3ash.ap Classa .ap, an unsynchroni6ed 3ashtable. Allows unordered lookup by key, usually a !tring. (t is thread safe if you only do lookups. 7therwise you must synchronise e4ternally, or use a 3ashtable. :o duplicates allowed.3ash!et Classa !et, a collection of uniue objects, without ability to lookup by key, usually a !tring. :ot ordered. 7ften used to maintain a list of legal values, e.g. state abbreviations. You can uickly find out if a given value is in the legal list.3ashtable Classa .ap, a synchronised 3ash.ap. Allows unordered lookup by key, usually a !tring. :ote, this is spelled 3ashtable not 3ash 0able.(dentity3ash.ap Class(t is like a 3ashtable. 8sed in manipulating graphswhere you have to keep track of which nodes havealready been visited. (n )ava version *.+ or later. (t compares with ;; instead of euals.#inked3ash.ap classa 3ash.ap that also threads the objects together, usually in insertion order. 0his way you can retrieve the elements in insertion order with almostno more overhead than a 3ash.ap. (n )ava version *.+ or later.#inked#ist classa #ist that behaves like 'ector, but implemented asa doubly linked chain of objects. 4"( /2To remove an element from the specified inde' of .rray,ist use%bject remove!int inde'" method.$t returns the element that was removed from the .rray,ist.2/%bject obj 8 array,ist.remove!3"(+earch an element of Java .rray,ist 1'ample/2To check whether the specified element e'ists in Java .rray,ist useboolean contains!%bject element" method.$t returns true if the .rray,ist contains the specified objct falseotherwise.2/ boolean bln?ound 8 array,ist.contains!404"(+ystem.out.println!47oes array,ist contain 0 @ 4 A bln?ound"( /2To get an inde' of specified element in .rray,ist useint inde'%f!%bject element" method.This method returns the inde' of the specified element in .rray,ist.$t returns -3 if not found.2/ int inde' 8 array,ist.inde'%f!494"(+ort elements of Java .rray,ist 1'ample /2To sort an .rray,ist object use Collection.sort method. This is astatic method. $t sorts an .rray,ist objectBs elements into ascending order.2/Collections.sort!array,ist"(10Copy 1lements of .rray,ist to Java *ector 1'ample/2To copy elements of Java .rray,ist to Java *ector usestatic void copy!,ist dst,ist ,ist source,ist" method of Collections class. This method copies all elements of source list to destination list. .fter copyinde' of the elements in both source and destination lists would be identical. The destination list must be long enough to hold all copied elements. $f it islonger than that the rest of the destination listBs elments would remainunaffected. 2/ //copy all elements of .rray,ist to *ector using copy method of Collections classCollections.copy!varray,ist"(Copy 1lements of %ne Java .rray,ist to .nother Java .rray,ist 1'ample/2To copy elements of one Java .rray,ist to another usestatic void copy!,ist dst,ist ,ist source,ist" method of Collections class. This method copies all elements of source list to destination list. .fter copyinde' of the elements in both source and destination lists would be identical. The destination list must be long enough to hold all copied elements. $f it islonger than that the rest of the destination listBs elments would remainunaffected. 2/ //copy all elements of .rray,ist to another .rray,ist using copy //method of Collections classCollections.copy!array,ist0array,ist3"(Create ,ist containing n Copies of +pecified %bject 1'ample/2To create a ,ist containing n copies of specified %bject usestatic ,ist nCopies!int n %bject obj" method of Java Collections class. This method returns immutable ,ist containing n copies of thespecified %bject.2/ ,ist list 8 Collections.nCopies!:4.4"(Create Java .rray,ist ?rom 1numeration 1'ample//create a *ector object*ector v 8 new *ector!"( 11//.dd elements to *ectorv.add!4.4"(v.add!4C4"(v.add!474"(v.add!414"(v.add!4?4"( +ystem.out.println!4*ector contains : 4 A v"( /2To create .rray,ist from any 1numeration usestatic .rray,ist list!1numeration e" method of Collections class. This method returns the .rray,ist containing the elements returned byspecified 1numeration object in order they are returned.2/ //=et 1numeration over *ector1numeration e 8 v.elements!"( //Create .rray,ist from 1numeration of *ector.rray,ist a,ist 8 Collections.list!e"(//create boolean arraysboolean;< bln.rray3 8 new boolean;44Three4"(tree-ap.put!4044Two4"(tree-ap.put!4:44?ive4"(tree-ap.put!4944?our4"( /2To get a Tail -ap from Java Tree-ap use+orted-ap tail-ap!%bject from)ey" method of Java Tree-ap class. This method returns the portion of Tree-ap whose keys are grater thanor e&ual to from)ey. 23/lease note that the +orted-ap returned by this method is backed bythe original Tree-ap. +o any changes made to +orted-ap will bereflected back to original Tree-ap.2/ +orted-ap sorted-ap 8 tree-ap.tail-ap!404"( +ystem.out.println!4Tail -ap Contains : 4 A sorted-ap"( /2/lease also note that- +orted-ap throws $llegal.rgument1'ception for any attempts to insert thekey less than from)ey. - sub-ap throws ClassCast1'ception if from)ey can not be compared using-apBs Comparators2/