Converting Between array and List Flashcards
Give the method signatures of the toArray method !
Object[] toArray() :
This method returns an array of Object containing all the elements of the collection.
EXAMPLE :
Collection<String> collection = new ArrayList<>();
collection.add("Apple");
collection.add("Banana");
collection.add("Cherry");</String>
// Convert collection to Object array Object[] objectArray = collection.toArray(); // Print the array for (Object obj : objectArray) { System.out.println(obj); }
<T> T[] toArray(T[] a) :
This method returns an array of type T containing all the elements of the collection. If the provided array is large enough, elements are placed into it; otherwise, a new array of the same type is created.
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
list.add("Date");
list.add("Elderberry");
// Create an array of Strings with fewer elements than the List
String[] smallArray = new String[3]; // This array is too small
// Convert the List to an array
String[] resultArray = list.toArray(smallArray);
// Print the resulting array
System.out.println("Resulting Array:");
for (String fruit : resultArray) {
System.out.println(fruit);
}
</String></T>
What is the main difference between the version that accepts an array parameter and the one that does not ?
Object[] toArray(): Always returns Object[].
<T> T[] toArray(T[] a): Returns an array of the type T[], which matches the type of elements in the collection.
</T>
Give the signature of the asList method !
public static <T> List<T> asList(T... a)</T></T>
EXAMPLE
String[] array = new String[]{“A”,”B”,”C”};
List<String> liste = Arrays.asList(array);
System.out.println(liste);// [A, B, C]</String>
Define an array backed List ?
Array-backed List: This is the List that is created using the original array, typically done with the Arrays.asList() method in Java.
What happens if we apply remove or add methods to an array backed list ?
Trying to add or remove elements from any list returned by the asList method will cause an UnsupportedOperationException
Give a characteristic of the asList method !
asList() takes varargs, which let you pass in an array or just type out the String values.
EXAMPLE :
List<String> list = Arrays.asList("A", "B", "C");
System.out.println(list); // Output: [A, B, C]</String>