Previously,
we have studied the
arraydata structure in
Chapter 7 of the
text book
When we discussed the
array, we alsolearned about
somesupport methods
in the
java.util.arraysclass
(),
such as:
Arrays.sort( arrayName ):
sort an array
Arrays.equals( array1, array2 ):
check if 2 arrays contains the same elements
Arrays.copyOf(arrayName, arrayName.length):
returns a copy of an array
Arrays.toString(arrayName):
returns a string of the elements in the array
and so on
Java's libraryalsocontainssupport methods for
ArrayList --
discussed next
Support methods for
ArrayList
The support methods for
ArrayList are
stored in the:
java.util.Collectionsclass
(online doc:)
We will discuss the followingsupport methods for:
Convertbetween an
array and an
ArrayList:
Converting
an array to
an ArrayList
Converting
an ArrayList to
an array
Sort an
ArrayList
Find the
maximum and
minimumvalue
stored in
an ArrayList
Shuffle
the elements stored
in an ArrayList
Converting an
Array
into an
ArrayListArray ⇒ ArrayList
To convert
an array to
an array list,
you instantiate
an
array listusing an array
as follows:
String[] myArray = {"red", "green", "blue"}; // Array to be converted
ArrayList<String> myList = new ArrayList<>( Arrays.asList(myArray) );
Arrays.asList(myArray)
returns a list of
elements in
myArray.
Alternately,
we canuse a
loop
and add the
elements one at a time
to the ArrayList:
String[] myArray = {"red", "green", "blue"};
ArrayList<String> myList = new ArrayList<>(); // Create ArrayList
// Add elements in myArray to myList
for (int i = 0; i < myArray.length; i++)
myList.add( myArray[i] );
Converting an
ArrayList
into an
ArrayArrayList ⇒ Array
To convert
an array list to
an array,
you use the
instance methodtoArray(myArray)
that
copies the
elements
in an ArrayList to
the arraymyArray:
ArrayList<String> myList = ... ; // ArrayList to be converted
String[] myArray = new String[ myList.size() ]; // Create array
myList.toArray( myArray ); // Copies elems in myList to myArray
Alternately,
we canuse a
loop
and copy the
elements one at a time
to the array:
ArrayList<String> myList = ... ; // ArrayList to be converted
String[] myArray = new String[ myList.size() ]; // Create array
for ( int i = 0; i < myArray.length; i++ ) // Loop to copy elements
myArray[i] = myList.get(i);
The java.util.Collectionsclass
contains a
(static)
shuffle(list)
method that
randomly shuffles the
elementsstored in
an ArrayList object:
Collections.shuffle( ArrayList )
Example:
public static void main(String[] args)
{
ArrayList<String> myList = new ArrayList<>();
myList.add("aaa"); myList.add("bbb"); myList.add("ccc");
myList.add("ddd"); myList.add("eee"); myList.add("fff");
System.out.println( myList ); // Original order
Collections.shuffle( myList ); // Shuffles a list
System.out.println( myList ); // Show new order
}