public static void main(String a[]){
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
List<String> strList = Arrays.asList(strArr);
System.out.println("Created List Size: "+strList.size());
System.out.println(strList);
I was looking for the explanation of the code
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
this line means that we are declaring a variable strArr
of string type and in the array we are declaring 5 variables is that correct
Then I am unable to clearly understand second line
List<String> strList = Arrays.asList(strArr);
is strList
an object of List<String>
?
With the below code you are converting your String array to a fixed size list.
List<String> strList = Arrays.asList(strArr);
While converting an Array to a List. You can perform all operation of List to your newly created fixed size list. Exmaple Sorting a List as below.
Collection.sort(strList);
But with the above code you cannot add element into your list. While adding element in list it will throw you an exception. Sample code as below.
String[] strArr = {"JAVA", "C++", "PERL", "STRUTS", "PLAY"};
List<String> strList = Arrays.asList(strArr);
strList.add("Spring"); // This line will throw exception
System.out.println("Created List Size: "+strList.size());
System.out.println(strList);
If you want to add element to your list you have to convert your String Array to List as below.
List<String> strList = new ArrayList<String>(Arrays.asList(strArr));
Hope this will help you to understand it