Jakarta Commons Cookbook notes(一)

jar name: commons-lang

 

一. Supplements to the java 2 platform

 

1. toString()

public void toString() {
  ReflectionToStringBuilder.toString(this);
}
 

 

2. hashCode()

public int hashCode() {
 return HashCodeBuilder.reflectionHashCode(this);
}
 

 

3. equal() 

public boolean equals(Object o){
 return EqualBuilder.reflectionEquals(this,o);
}
 

 

4. compareTo() 

public int compareTo(Object o) {
  return CompareToBuilder.reflectionCompare(this,o);
}
 

 

5. print a array

int[] intArray = new int[] {2,3,4,5,6}
ArrayUtils.toString(intArray));
 

 

6. cloning and reversing arrays

long array[] array = {1,3,2,3,5,6};
long[] reversed = ArrayUtils.clone(array);
ArraysUtils.reverse(reversed);

 

 

7. transforming between object arrays and primitive array

long primitiveArray = new long[] {12,100,2929,3223};
Long[] objectArray = ArrayUtils.toObject(primitiveArray);

// null values in the object array are stored as Double.NaN
ArrayUtils.toPrivimitive(doubleObject,Double.NaN);
 

 

8. find items in an array

String[] stringArray = {"red","orange","blue","brown","red"};
boolean containsBlue = ArraysUtils.contains(stringArray,"blue");
int indexOfRed = ArraysUtils.indexOf(stringArray,"red");
int lastIndexOfRed = ArraysUtils.lastIndexOf(stringArray,"red");
 

 

9. creating a map from multidimensional array

Object[] weightArray = new Object[][] {{"H", new Double(1.0003)},
							     {"He", new Double(4.0002)},
                               {"Li", new Double(6.032)});
Map weights = ArraysUtils.toMap(weightArray);
 

 

10. formatting dates

// thead-safe formatter for java
DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date());
 

 

11. Rounding date objects

DateUtils.round(new Date(), Calendar.HOUR);
DateUtils.round(new Date(), Calendar.DATE_OF_MONTH);
DateUtils.round(new Date(), Calendar.YEAR);
 

 

12. truncating date object

DateUtils.truncat(new Date(), Calendar.MONTH);
DateUtils.truncat(new Date(), Calendar.HOUR);
 

 

13. Generating unique numberic identifiers

LonIdentifierFactory idfactory = IdentifierUtils.LongGenerator(false,0);
idFactory.nextLongIdentifier();
 

 

14. measure time

StopWatch clock = new StopWatch();
clock.start();
clock.stop();
clock.getTime();
clock.reset();
 

 

 

 

 

 

你可能感兴趣的:(commons)