ParthaKuchana.com   Stocks & Technology
Arrays.asList Explained
Arrays.asList Explained



import java.util.Arrays;
import java.util.List;

public class Test {

public static void main(String[] args) {
/*
List numbers = Arrays.asList(1, 2, 3, 4, 5);
System.out.println(numbers); // Output: [1, 2, 3, 4, 5]
System.out.println(numbers.size());

//Single Input:
List single = Arrays.asList("Hello");
System.out.println(single); // Output: [Hello]
System.out.println(single.size());


//Empty List:
List empty = Arrays.asList();
System.out.println(empty); // Output: []



//Key Characteristics:
//Fixed Size: The list returned by Arrays.asList is of fixed size. You cannot add or remove elements, though you can modify existing ones.
List list = Arrays.asList(1, 2, 3);
// list.add(4); // Throws UnsupportedOperationException
list.set(0, 10); // Allowed
System.out.println(list); // Output: [10, 2, 3]
*/


//Backed by Array: The list is backed by the original array.
//Modifying the array modifies the list and vice versa.
//Non-Primitive Types: It works with objects and not with primitive arrays directly.
/*
int[] nums = {1, 2, 3};
List list = Arrays.asList(nums); // This creates a list with a single element: the array itself.
System.out.println(list.size()); // Output: 1
System.out.println(list.get(0)); // Output: [I@
*/

//To convert a primitive array, you can use:
Integer[] nums = {1, 2, 3};
List list = Arrays.asList(nums);
System.out.println(list); // Output: [1, 2, 3]

}

}

© 2024 parthakuchana.com