Java Reference
In-Depth Information
There are also a number of useful static methods defined on the Arrays class:
int [] intarray = new int [] { 10 , 5 , 7 , - 3 }; // An array of integers
Arrays . sort ( intarray ); // Sort it in place
// Value 7 is found at index 2
int pos = Arrays . binarySearch ( intarray , 7 );
// Not found: negative return value
pos = Arrays . binarySearch ( intarray , 12 );
// Arrays of objects can be sorted and searched too
String [] strarray = new String [] { "now" , "is" , "the" , "time" };
Arrays . sort ( strarray ); // sorted to: { "is", "now", "the", "time" }
// Arrays.equals compares all elements of two arrays
String [] clone = ( String []) strarray . clone ();
boolean b1 = Arrays . equals ( strarray , clone ); // Yes, they're equal
// Arrays.fill initializes array elements
// An empty array; elements set to 0
byte [] data = new byte [ 100 ];
// Set them all to -1
Arrays . fill ( data , ( byte ) - 1 );
// Set elements 5, 6, 7, 8, 9 to -2
Arrays . fill ( data , 5 , 10 , ( byte ) - 2 );
Arrays can be treated and manipulated as objects in Java. Given an arbitrary object
o , you can use code such as the following to find out if the object is an array and, if
so, what type of array it is:
Class type = o . getClass ();
if ( type . isArray ()) {
Class elementType = type . getComponentType ();
}
Lambda Expressions in the Java Collections
One of the major reasons for introducing lambda expressions in Java 8 was to facili‐
tate the overhaul of the Collections API to allow more modern programming styles
to be used by Java developers. Until the release of Java 8, the handling of data struc‐
tures in Java looked a little bit dated. Many languages now support a programming
style that allows collections to be treated as a whole, rather than requiring them to
be broken apart and iterated over.
In fact, many Java developers had taken to using alternative data structures libraries
to achieve some of the expressivity and productivity that they felt was lacking in the
Collections API. The key to upgrading the APIs was to introduce new methods that
would accept lambda expressions as parameters—to define what needed to be done,
rather than precisely how .
Search WWH ::




Custom Search