Apache Commons CollectionsTags: collectionsapachehashmapcommandobjectjavadoc 2012-05-09 10:13 1070 people read Comments (0) Favorites Report Category: Java Programming (74)
Directory (?) [+]Original Http://blog.csdn.net/sunjavaduke/archive/2008/03/24/2214806.aspx This paper briefly introduces the content of collections frame in Apache Commons. This article is mainly based on the Apache official website overview, userguide and Javadoc translation. If there is reprint, please declare the source. Commons Collections: The Java Collection Framework is a major complement to JDK1.2 by JDK 1.3. The Java Collection Framework contains a number of powerful data structures that speed up the development of many important Java programs. Since then, the collection framework has become the open standard for Java processing collections. Commons-collections provides new interfaces, implementations, and tools based on the JDK's collection framework. It has the following features: ® bag interface: For collections that contain multiple copies of an object ® buffer interface: For collection classes with order, such as FIFOs (first-in first Out) ® bidimap (bidirectional mapping) : A value lookup key can also be found by a key lookup value ® map iterator: Provides a quick iteration of the mappings ® encapsulates type checking to ensure that instances of a particular class can be added to the collection ® the conversion is encapsulated. Converts an object in a collection to a type ® the collection, making multiple collections look like a collection ® ordered mapping and set, keeping the order of element additions, including a LRU based map® identity map that can be given to the object = = To compare objects, instead of ® reference mappings based on the Equals method, you can allow the key and/or value to be controlled for recycling ® the implementation of many comparators ® many iterators ® an adapter from an array or enumeration to a collection ® Set properties used to test or create a typical set theory, such as with, or, closuresUser's Guide:Commons-collections provides a large number of classes to help with day-to-day programming. This part mainly introduces the key characteristics of some collections. Note Synchronization Commons-collections uses a synchronous design method similar to the standard Java collection. Most implementations of collections, mappings, and bag are not thread-safe without adding additional synchronization methods. The Synchronizexxx method of the collection is one of these implementations that allows the collection to be synchronized in multithreaded applications. A class-level Javadoc should indicate whether a particular implementation is secure if there is no additional synchronization mechanism for multithreaded access. If it is not specifically pointed out to be thread-safe, then it is considered necessary to synchronize.Tool Class:Each major collection interface has a utility class. Therefore, the utility class for set and SortedSet interfaces is setutils. These utility classes provide a common way to manipulate collection types. The basic methods are contained in the utility class of the two root set interfaces, namely, Collectionutils and Maputils. Because all other collection interfaces are integrated with collection or map, collectionutils and Maputils can be extended. Common methods include intersection operations, counting operations, iterative operations, logical operations, and type casting operations. The utility class also provides access to the collection's encapsulated classes, similar to the way JDK collections classes do.Maps: The map interface in the map iteration jdk is difficult to iterate over. API users always need to iterate through entryset or keyset. Commons-collectons now provides a new interface-mapiterator to allow simple iterations of maps. Iterablemap map = new HashMap (); Mapiterator it = Map.mapiterator (); while (It.hasnext ()) { Object key = It.next (); Object value = It.getvalue (); It.setvalue (NewValue); The ordered map Commons-collections provides maps with a new interface, Orderedmap, which is sequential, but not sorted. Linkedmap and Listorderedmap (wrappers) are two implementations of this interface. This interface supports map iterations, while allowing forward and backward iterations of the map. Orderedmap map = new HashMap (); Map.put ("FIVE", 5); Map.put ("SIX", 6); Map.put ("SEVEN", 7); Map.firstkey (); //returns "FIVE" Map.nextkey ("FIVE"); //returns "SIX" Map.nextkey ("SIX"); //returns "SEVEN" Biddirectional Maps Bidirectional mapping commons-collections provides a new connectionThe level of the mouth, used to support bidirectional mapping, that is, the Bidimap interface. You can find value by key, or you can find key by value. Bidimap bidi = new Treebidimap (); Bidi.put ("SIX", "6"); Bidi.get ("SIX"); //returns "6" Bidi.getKey ("6") ; //returns "SIX" Bidi.removevalue ("6"); //removes the mapping bidimap inverse = Bidi.inversebidimap (); //returns A The map with keys and values swapped the corresponding interfaces for both ordered and sorted two-way maps. The implementation of the interface is provided for each bidirectional map type.queues&buffers queues and buffersThe buffer interface is used to support queues and buffers. These interfaces represent the order in which the collection can define deletes. Buffer buffer = new Unboundedfifobuffer (); Buffer.add ("one"); Buffer.add ("two"); Buffer.add ("THREE"); Buffer.remove (); Removes and returns the next in order, ' one ' as this is a FIFO buffer.remove (); Removes and returns the next in order, the interface implementations of the "two" as This is a FIFO FIFO (queue), LIFO (stack), and priority (according to the sequence of the comparator) have been provided.Bags The bag interface is used to support bag. It is used to represent a combination of multiple copies containing an object. Bag Bag = new Hashbag (); Bag.add ("One", 6); //add 6 copies of "one" Bag.remove ("One", 2); //removes 2 Copies of "One" Bag.getcount ("one"); //returns 4 has corresponding interface implementations for sorting and sorting bag. Here is a translation of an article in the Internet, Source: HTTP://WWW.DEVX.COM/JAVA/ARTICLE/29392/0/PAGE/3 JDK does not already have a Java collection framework, Why use the Apache collection? This is because Apache's collection is a complement and enhancement of the JDK collection, which provides more interfaces and implementation classes. Even it should be part of the JDK. Here are some of the characteristics I prefer: ® bag interface ® Fixed sized map, LRU (most recently least used algorithm) map and double (dual) map® object array and map iterator ® map multikey® A large number of tool classes that provide shortcuts to using the API wrappers, which provide a custom side for most classesThe collections class is organized according to the package structure listed below: Org.apache.commons.collections org.apache.commons.collections.bag Org.apache.commons.collections.bidimap Org.apache.commons.collections.buffer Org.apache.commons.collections.collection org.apache.commons.collections.comparators Org.apache.commons.collections.functors org.apache.commons.collections.iterators Org.apache.commons.collections.keyvalue org.apache.commons.collections.list Org.apache.commons.collections.map Org.apache.commons.collections.setorg.apache.commons.collectionsThis package defines an interface that is implemented by other packages, as a common class of factory classes that can instantiate a collection class or a collection of encapsulated classes. Some of the more important classes are Arraystack, Beanmap, ExtendedProperties, Fastarraylist, Fasthashmap and Fasttreemap. The details of these classes are contained in Javadoc, and the following is just a brief introduction to the actual application of each class: The Arraystack:arraystack class implements the stack interface and is based on ArrayList for use in a single-threaded environment. For example, if you want to use a stack for some processing in one method, this class is better at performance than in stack (JDK1.4.2 uses vectors). Beanmap: Just like the JButton in the swing GUI, using Beanmap, you can even handle a map as a javabean. When you design a GUI that displays data sources or application configuration properties, a map can be dragged and dropped on the screen (d&d). ExtendedProperties: This is a very useful class. Similar to Java.util.Properties, it contains a load method for loading configuration information, but this class has the following benefits: # attribute values can be spread across multiple lines # provides methods for obtaining non string values. For example, the Getfload method is used to get a value of a fload type. This does not require the use of the wrapper method to convert the obtained string value. Fastarraylist, Fasthashmap, Fasttreemap: These classes can be used in multithreaded environments, if there are many read-only operations. These classes are based on ArrayList, HashMap, and TreeMap respectively.Org.apache.commons.collections.bagIf you need to add multiple copies of an object to a list, the class below the package becomes very useful. In this case, many developers add objects to a ArrayList, and then add them every day to determine whether or not to add a given type of object. Online shopping carts are a real demand for this situation. The disadvantage of this approach is the lack of memory and speed. A good design to solve the above requirements is to save only one copy of the object, while adding the same type of entity, only increase the value of the counter. The Hashbag and Treebag classes (respectively, based on HashMap and TREEMAP) meet this requirement.
As shown in the following example:
Package in.co.narayanan.commons.collections.bag;
Import Junit.framework.TestCase;
Import Org.apache.commons.collections.Bag;
Import Org.apache.commons.collections.bag.HashBag;
/**
* This domain represents a order placed by the customer.
*
* @author Narayanan A R
*/
public class Order {
Private Bag orderedproducts;
Public order () {
orderedproducts = new Hashbag ();
}
public void Addproduct (Product p) {
Orderedproducts.add (P);
}
public int countwindowslicenses () {
Return Orderedproducts.getcount (product.windows);
}
public int countlinuxlicenses () {
Return Orderedproducts.getcount (Product.linux);
}
}
Class Product {
OSType is an enum
public static final Product WINDOWS = new product (ostype.windows);
public static final Product LINUX = new product (ostype.linux);
public static final Product MAC = new product (OSTYPE.MAC);
public static final Product Hpunix = new product (Ostype.hpunix);
private int quantity;
private int version;
private float Prize;
Private OSType type;
Public Product (OSType type) {
This.type = type;
}
public int getquantity () {
return quantity;
}
public void setquantity (int quantity) {
this.quantity = quantity;
}
public int getversion () {
return version;
}
public void setversion (int version) {
This.version = version;
}
public float getprize () {
return prize;
}
public void Setprize (float prize) {
This.prize = Prize;
}
Public OSType GetType () {
return type;
}
public void SetType (OSType type) {
This.type = type;
}
@Override
public boolean equals (Object o) {
if (o instanceof Product) {
Return ((Product) O). GetType (). Equals (This.gettype ());
}
return Super.equals (o);
}
@Override
public int hashcode () {
return Type.hashcode ();
}
@Override
Public String toString () {
return type.tostring ();
}
}
Class Testorder extends TestCase {
public void Testorder () {
Order order = New Order ();
Order.addproduct (New Product (ostype.windows));
Order.addproduct (New Product (ostype.windows));
Order.addproduct (New Product (ostype.windows));
Order.addproduct (New Product (Ostype.linux));
Order.addproduct (New Product (Ostype.linux));
Order.addproduct (New Product (Ostype.hpunix));
Order.addproduct (New Product (OSTYPE.MAC));
int licenses;
licenses = Order.countwindowslicenses ();
Assertequals (3, licenses);
licenses = Order.countlinuxlicenses ();
Assertequals (2, licenses);
}
}
By debugging, when you run to the red line above, the member variable of the order orderedproducts the contents of: (ToString display content)
[2:linux,1:mac,1:hpunix,3:windows]
That is, you actually store only one copy of an object, and then use numbers to identify the number.
The size of the Orderedproducts member HashMap object is 4.
Org.apache.commons.collections.bidimap
Many Java developers use two HashMap to get a key value by passing a value as a key to another hashmap. Normally, you need to handle the same name and value, in which case the value can be the key (because the key is unique in the map and the value is not unique).
An example of Org.apache.commons.collections.bidimap is a prototype adapter that integrates the PeopleSoft and Siebel command line processing engines, assuming that each command in one engine has the same counterpart in the other. The related classes can be found in In.co.narayanan.commons.collections.bidimap. These classes can be understood through Siebelpeoplesoftconnector, siebelpeoplesoftconnector as adapters, and contain Bidimap objects. When a request is received to process the Siebel command, the corresponding PeopleSoft command is obtained from BIDIMAP and then transmitted to the PeopleSoft command engine. Vice versa. The sample code contains only one outline of the application.
/**
*definescontractforthesystemstoconsumeagiven
*command.
*
* @authorNarayananAR
*/
Publicinterface Icommandconsumer {
Object consume (String command, object arg);
}
Class Siebelcommandconsumer implements Icommandconsumer {
public object consume (String command, Object Arg) {
SYSTEM.OUT.PRINTLN ("Processing Siebel command:" + command);
System.out.println ("ARG:" + arg);
Return "SIEBEL:" + command + "-successful";
}
}
Class Peoplesoftcommandconsumer implements Icommandconsumer {
public object consume (String command, Object Arg) {
SYSTEM.OUT.PRINTLN ("Processing PeopleSoft command:" + command);
System.out.println ("ARG:" + arg);
Return "PEOPLESOFT:" + command + "-successful";
}
}
Import Org.apache.commons.collections.bidimap.TreeBidiMap;
Import Org.apache.commons.collections.BidiMap;
/**
*responsibleforadaptingboththesystem ' Scommands.
*
* @authorNarayananAR
*/
Publicclass Siebelpeoplesoftconnector {
Private Icommandconsumer PeopleSoft;
Private Icommandconsumer Siebel;
Private Bidimap Commandmap;
Public Siebelpeoplesoftconnector (Icommandconsumer PeopleSoft,
Icommandconsumer Siebel) {
This.peoplesoft = PeopleSoft;
This.siebel = Siebel;
Commandmap = Preparecommandmapping ();
}
Private Bidimap preparecommandmapping () {
Bidimap map = new Treebidimap ();
Map.put ("Start", "Init");
Map.put ("Exit", "quit");
Map.put ("delete", "remove");
return map;
}
/**
*delegatesthecalltothepeoplesoftcommandenginebyfetchingthemappedcommand.
*
* @paramcommandSiebelcommand
* @paramargArgumentifany
* @returnResultreturnedfromPeopleSoftcommandengine
*/
public Object Processsiebelcommand (String command, Object Arg) {
Returnpeoplesoft.consume ((String) commandmap.get (command), ARG);
}
/**
*delegatesthecalltothesiebelcommandenginebyfetchingthemappedcommand.
*
* @paramcommandPeopleSoftcommand
* @paramargArgumentifany
* @returnResultreturnedfromSiebelcommandengine
*/
Public Object Processpeoplesoftcommand (Str