Java Reference
In-Depth Information
Finally, nCopies() returns an immutable List that contains a specified number of
copies of a single specified object:
List < Integer > tenzeros = Collections . nCopies ( 10 , 0 );
Arrays and Helper Methods
Arrays of objects and collections serve similar purposes. It is possible to convert
from one to the other:
String [] a ={ "this" , "is" , "a" , "test" }; // An array
// View array as an ungrowable list
List < String > l = Arrays . asList ( a );
// Make a growable copy of the view
List < String > m = new ArrayList < String >( l );
// asList() is a varargs method so we can do this, too:
Set < Character > abc = new HashSet < Character >( Arrays . asList ( 'a' , 'b' , 'c' ));
// Collection defines the toArray method. The no-args version creates
// an Object[] array, copies collection elements to it and returns it
// Get set elements as an array
Object [] members = set . toArray ();
// Get list elements as an array
Object [] items = list . toArray ();
// Get map key objects as an array
Object [] keys = map . keySet (). toArray ();
// Get map value objects as an array
Object [] values = map . values (). toArray ();
// If you want the return value to be something other than Object[],
// pass in an array of the appropriate type. If the array is not
// big enough, another one of the same type will be allocated.
// If the array is too big, the collection elements copied to it
// will be null-filled
String [] c = l . toArray ( new String [ 0 ]);
In addition, there are a number of useful helper methods for working with Java's
arrays, which are included here for completeness.
The java.lang.System class defines an arraycopy() method that is useful for
copying specified elements in one array to a specified position in a second array.
The second array must be the same type as the first, and it can even be the same
array:
s
a
char [] text = "Now is the time" . toCharArray ();
char [] copy = new char [ 100 ];
// Copy 10 characters from element 4 of text into copy,
// starting at copy[0]
System . arraycopy ( text , 4 , copy , 0 , 10 );
// Move some of the text to later elements, making room for insertions
System . arraycopy ( copy , 3 , copy , 6 , 7 );
 
Search WWH ::




Custom Search