Java Reference
In-Depth Information
// s1 has enough space to copy all ArrayList elements.
// al.toArray(s1) returns s1 itself
System.out.println("s1 == s2:" + (s1 == s2));
System.out.println("s1:" + Arrays.toString(s1));
System.out.println("s2:" + Arrays.toString(s2));
// Create an array of string with 1 element.
s1 = new String[1];
s1[0] = "hello" ; // Store hello in first element
// Copy ArrayList to the array s1
s2 = al.toArray(s1);
/* Since s1 doesn't have sufficient space to copy all ArrayList elements,
al.toArray(s1) creates a new String array with 3 elements in it. All elements of
arraylist are copied to new array. Finally, new array is returned. Here, s1 ==
s2 is false. s1 will be untouched by the method call.
*/
System.out.println("s1 == s2:" + (s1 == s2));
System.out.println("s1:" + Arrays.toString(s1));
System.out.println("s2:" + Arrays.toString(s2));
}
}
ArrayList:[cat, dog, rat]
s1 == s2:true
s1:[cat, dog, rat]
s2:[cat, dog, rat]
s1 == s2:false
s1:[hello]
s2:[cat, dog, rat]
Summary
An array is a data structure to store multiple data values of the same type in memory. All array elements are allocated
contiguous space in memory. Array elements are accessed using their indexes. Arrays use zero-based indexing.
The first element has an index of zero.
Arrays in Java are objects. Java supports fixed-length arrays. That is, once an array is created, its length cannot be
changed. Use an ArrayList if you need a variable-length array. The ArrayList class provides a toArray() method to
convert its elements to an array. Java supports multi-dimensional arrays in the form of ragged arrays that are arrays of
arrays. You can clone an array using the clone() method. A shallow-cloning is done for reference arrays.
 
Search WWH ::




Custom Search