---
title: "The Common Java cookbook 笔记(1)"
author: "webdd"
date: "2009-08-15T14:19:41Z"
tags: []
slug: "the-common-java-cookbook-1"
draft: false
lastmod: "2009-08-15T14:25:33Z"
id: 450110
url: "https://webdd.iteye.com/blog/450110"
---

**1.4.1. Problem**  
You want to automate the creation of toString( ) methods.  
**1.4.2. Solution**  
Use the Commons Lang ReflectionToStringBuilder or ToStringBuilder and ToStringBuilder to create toString()  
methods. The following code is an example of a toString( ) method, which uses a reflection builder:

```
import org.apache.commons.lang.builder.ReflectionToStringBuilder;








public String toString() {








return ReflectionToStringBuilder.reflectionToString(this);








}
```

 

**1.5.1. Problem**  
You need to automate toString( ) while retaining control over the output, contents, and formatting.  
**1.5.2. Solution**  
In addition to the ReflectionToStringBuilder, Commons Lang provides for customization via the ToStringBuilder and  
ToStringStyle class. From the previous recipe, if you only want the PoliticalCandidate toString( ) method to print  
lastName and firstName, use the ToStringBuilder class and pass in a ToStringStyle object. The following example  
demonstrates a toString( ) method implementation that customizes both style and content:

 

```
import org.apache.commons.lang.builder.ToStringBuilder;


import org.apache.commons.lang.builder.ToStringStyle;


public String toString( ) {


return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)


.append("lastName", lastName)


.append("firstName", firstName)


.toString( );


}
```

 

 

**1.6.1. Problem**  
You need a way to automatically implement equals() and hashCode( ) methods.  
**1.6.2. Solution**  
Commons Lang EqualsBuilder and HashCodeBuilder provide methods to automate both the equals( ) and hashCode(  
). Example 1-2 briefly demonstrates these two builders using the PoliticalCandidate bean from the previous two  
recipes.

 

 

```
import org.apache.commons.lang.builder.EqualsBuilder;


import org.apache.commons.lang.builder.HashCodeBuilder;


// Member variables - omitted for brevity


// Constructors - omitted for brevity


// get/set methods - omitted for brevity


// A hashCode which creates a hash from the two unique identifiers


public int hashCode( ) {


return new HashCodeBuilder(17, 37)


.append(firstName)


.append(lastName).toHashCode( );


}


// An equals which compares two unique identifiers


public boolean equals(Object o) {


boolean equals = false;


if ( o != null &&


PoliticalCandidate.class.isAssignableFrom(o.getClass()) ) {


PoliticalCandidate pc = (PoliticalCandidate) o;


equals = (new EqualsBuilder( )


.append(firstName, pc.firstName)


.append(lastName, pc.lastName)).isEquals( );


}


return equals;


}
```

 

 

 

 

**1.7.1. Problem**  
You need a quick way to implement compareTo( ) methods.  
**1.7.2. Solution**  
Commons Lang CompareToBuilder provides a builder for compareTo( ) methods. CompareToBuilder can perform a  
comparison via reflection, or a comparison can be customized by passing parameters to an instance of CompareToBuilder.  
The following example demonstrates the use of the reflection builder to implement a compareTo( ) method. This  
implementation compares all nonstatic and nontransient member variables in both classes.

 

 

 

```
import org.apache.commons.lang.builder.CompareToBuilder;


// Build a compareTo function from reflection


public int compareTo(Object o) {


return CompareToBuilder.reflectionCompare(this, obj);


}
```

 

 

 

 

 

 

 

**1.8.1. Problem**  
You need to print the contents of an array.  
**1.8.2. Solution**  
Use ArrayUtils.toString() to print the contents of an array. This method takes any array as an argument and prints out  
the contents delimited by commas and surrounded by brackets:

 

 

 

```
int[] intArray = new int[] { 2, 3, 4, 5, 6 };


int[] multiDimension = new int[][] { { 1, 2, 3 }, { 2, 3 }, {5, 6, 7} };


System.out.println( "intArray: " + ArrayUtils.toString( intArray ) );


System.out.println( "multiDimension: " + ArrayUtils.


toString( multiDimension ) );
```

 

 

 

 

 

 

 

**1.9.1. Problem**  
You need to reverse and clone the contents of an array.  
   
**1.9.2. Solution**  
Use ArrayUtils.clone() and ArrayUtils.reverse() methods from Commons Lang. Example 1-5 demonstrates the  
reversal and cloning of a primitive array full of long primitives.

 

```
import org.apache.commons.lang.ArrayUtils;


long[] array = { 1, 3, 2, 3, 5, 6 };


long[] reversed = ArrayUtils.clone( array );


ArrayUtils.reverse( reversed );


System.out.println( "Original: " + ArrayUtils.toString( array ) );


System.out.println( "Reversed: " + ArrayUtils.toString( reversed ) );
```

 

 

**1.10.1. Problem**  
You need a way to convert an object array to a primitive array.  
**1.10.2. Solution**  
Use ArrayUtils.toObject() and ArrayUtils.toPrimitive() to translate between primitive arrays and object arrays.  
The following example demonstrates the translation from a primitive array to an object array and vice versa:

 

```
import org.apache.commons.lang.ArrayUtils;


long[] primitiveArray = new long[] { 12, 100, 2929, 3323 };


Long[] objectArray = ArrayUtils.toObject( primitiveArray );





Double[] doubleObjects = new Double[] { new Double( 3.22, 5.222, 3.221 ) };


double[] doublePrimitives = ArrayUtils.toPrimitive( doubleObject );
```

 

 

 

 

 

**1.11.1. Problem**  
You need to test an array to see if it contains an element. If the array contains the element, you need the index of the  
matching element.  
**1.11.2. Solution**  
Use ArrayUtils.contains() to see if an array contains a specified element, and use ArrayUtils.indexOf( ) or  
ArrayUtils.lastIndexOf( ) to find the position of a matching element. The following example demonstrates the use of  
these three methods:

 

```
import org.apache.commons.lang.ArrayUtils;


String[] stringArray = { "Red", "Orange", "Blue", "Brown", "Red" };


boolean containsBlue = ArrayUtils.contains( stringArray, "Blue" );


int indexOfRed = ArrayUtils.indexOf( stringArray, "Red");


int lastIndexOfRed = ArrayUtils.lastIndexOf( string, "Red" );


System.out.println( "Array contains 'Blue'? " + containsBlue );


System.out.println( "Index of 'Red'? " + indexOfRed );


System.out.println( "Last Index of 'Red'? " + lastIndexOfRed );
```

 

**1.12.1. Problem**  
You need to create a Map from a multidimensional array.  
**1.12.2. Solution**  
Use ArrayUtils.toMap() to create a Map from a two-dimensional array (Object\[]\[]). Example 1-8 demonstrates the  
creation of such a Map. Example 1-8 takes an Object\[]\[] representing atomic symbols and atomic weights and turns it  
into a Map retrieving the atomic weight for hydrogen.

 

 

```
import org.apache.commons.lang.ArrayUtils;


Object[] weightArray =


new Object[][] { {"H" , new Double( 1.007)},


{"He", new Double( 4.002)},


{"Li", new Double( 6.941)},


{"Be", new Double( 9.012)},


{"B", new Double(10.811)},


{"C", new Double(12.010)},


{"N", new Double(14.007)},


{"O", new Double(15.999)},


{"F", new Double(18.998)},


{"Ne", new Double(20.180)} };


// Create a Map mapping colors.


Map weights = ArrayUtils.toMap( weightArray );


Double hydrogenWeight = map.get( "H" );
```

 

 

**1.13.1. Problem**  
You need to format a date, and SimpleDateFormat is not thread-safe. You are also looking for standard International  
Organization of Standards (ISO) date formats.  
**1.13.2. Solution**  
Use FastDateFormat, a thread-safe formatter for Java Date objects, and use public static instances of FastDateFormat on  
DateFormatUtils, which correspond to ISO date and time formatting standards defined in ISO 8601. The following  
example outputs the international standard for representing a date and time in a given time zone:

 

 

```
Date now = new Date( );


String isoDT = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format( now );


System.out.println( "It is currently: " + isoDT );
```

 

 

 

**1.14.1. Problem**  
You need to round a date to the nearest second, minute, hour, day, month, or year.  
   
**1.14.2. Solution**  
Use DateUtils to round Date objects to the nearest Calendar field. DateUtils.round() can round to almost every  
Calendar field, including Calendar.SECOND, Calendar.MINUTE, Calendar.HOUR, Calendar.DAY\_OF\_MONTH,  
Calendar.MONTH, and Calendar.YEAR. The following example demonstrates the use of DateUtils.round( ):

```
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
FastDateFormat dtFormat = DateFormatUtils.ISO_DATETIME_FORMAT;
Date now = new Date( );
Date nearestHour = DateUtils.round( now, Calendar.HOUR );
Date nearestDay = DateUtils.round( now, Calendar.DAY_OF_MONTH );
Date nearestYear = DateUtils.round( now, Calendar.YEAR );
System.out.println( "Now: " + dtFormat.format( now ) );
System.out.println( "Nearest Hour: " + dtFormat.format( nearestHour ) );
System.out.println( "Nearest Day: " + dtFormat.format( nearestDay ) );
System.out.println( "Nearest Year: " + dtFormat.format( nearestYear ) );
```

 

 

**1.15.1. Problem**  
You need to truncate a date to a calendar field.  
**1.15.2. Solution**  
Use DateUtils.truncate() to throw out all fields less significant than the specified field. When a Date is truncated to the  
   
Calendar.MONTH field, DateUtils.truncate( ) will return a Date object set to the first instance of the month. The day,  
hour, minute, second, and millisecond field will each contain the minimum possible value for that field. Example 1-9  
truncates a date at the month field and the hour field.

 

 

 

```
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.lang.time.DateFormatUtils;
FastDateFormat dtFormat = DateFormatUtils.ISO_DATETIME_FORMAT;
Date now = new Date( );
Date truncatedMonth = DateUtils.truncate( now, Calendar.MONTH );
Date truncatedHour = DateUtils.truncate( now, Calendar.HOUR );
System.out.println( "Now: " + dtFormat.format( now ) );
System.out.println( "Truncated Month: "
+ dtFormat.format( truncatedMonth ) );
System.out.println( "Truncated Hour: "
+ dtFormat.format( truncatedHour ) );
```

 

 

**1.18.1. Problem**  
You need to validate parameters passed to a method. You would prefer one line of code to test that a method parameter is  
valid.  
**1.18.2. Solution**  
Use Validate to check method parameters. Validate can check for empty or null parameters, as well as evaluate any  
logical conditions. Example 1-18 demonstrates the use of Validate to perform a few simple validations.

 

 

```
import org.apache.commons.lang.Validate;
public doSomething( int param1, Object[] param2, Collection param3 ) {
Validate.isTrue( param1 > 0, "param must be greater than zero" );
Validate.notEmpty( param2, "param2 must not be empty" );
Validate.notEmpty( param3, "param3 must not be empty" );
Validate.noNullElements( param3, "param3 cannot contain null elements" );
// do something complex and interesting
}
```

 

 

 

**1.19.1. Problem**  
You need to determine how much time has elapsed during the execution of a block of code.  
**1.19.2. Solution**  
Use StopWatch to measure the time it takes to execute a section of code. Example 1-20 demonstrates the use of this class  
to measure the time it takes to perform simple arithmetic operations.

 

 

 

```
import org.apache.commons.lang.time.StopWatch;
StopWatch clock = new StopWatch( );
System.out.println("Time to Math.sin(0.34) ten million times?" );
clock.start( );
for( int i = 0; i < 100000000; i++ ) {
Math.sin( 0.34 );
}
clock.stop( );
System.out.println( "It takes " + clock.getTime( ) + " milliseconds" );
clock.reset( );
System.out.println( "How long to multiply 2 doubles one billion times?" );

clock.start( );
for( int i = 0; i < 1000000000; i++) {
double result = 3423.2234 * 23e-4;
}
clock.stop( );
System.out.println( "It takes " + clock.getTime( ) + " milliseconds." );
```