Converting Between array and List Flashcards

1
Q

Give the method signatures of the toArray method !

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the main difference between the version that accepts an array parameter and the one that does not ?

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Give the signature of the asList method !

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Define an array backed List ?

A

Array-backed List: This is the List that is created using the original array, typically done with the Arrays.asList() method in Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What happens if we apply remove or add methods to an array backed list ?

A

Trying to add or remove elements from any list returned by the asList method will cause an UnsupportedOperationException

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Give a characteristic of the asList method !

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly