How to declaration of arrayList and add data and print:
import java.util.*;
public class ArrayList
{
public static void main(String args[])
{
ArrayList<Integer> arrL = new ArrayList<Integer>();
arrL.add(10);
System.out.println("Array list element:"+arrL.get(0));
}
}
-----------------------------------------------------------------------------------------------------------
Task 1:
·
Create an arraylist of strings named
student and apply given methods on array list.
o
Add name of students in arrayList
§ Ali
§ Ahmad
§ Umar
§ Talha
Hint: To add names use (Arrays.asList())
·
Create a static function named display(ArrayList<String> students)
and call it after each of following steps and also print a blank line after
each step.
·
Add two more students at the end of
students list using students.add()
o
1)Tooba 2) Waleed
·
Print the size of list.
·
Add “Hamza” in the start of students.
·
Add “Rizwan” as second element of list.
·
Sort list of students
·
Remove “Tooba” from list.
·
Remove last element from list.
Hint: To remove last element use (size()-1)
·
Display second element from list.
·
Update name of first student. New name
should be “Muhammad Waleed”
·
Remove the first name.
·
Remove all elements from list.
S
S Solution:
g
package com.mycompany.arraylist;
import java.util.*;
/ **
*
* @author HASHMI
*/
public class ArrayList1 {
public static void main (String[] args)
{
ArrayList<String> student = new ArrayList<String>();
System.out.println("initial size: " + student.size() );
student.add("Ali");
student.add("Ahmad");
student.add("umer");
student.add("Talha");
display(student);
student.add("Tooba");
student.add("Waleed");
System.out.println("new size of arrayList: " + student.size() );
student.add(0,"Hamza");
student.add(1,"Rizwan");
display(student);
student.remove("Tooba");
display(student);
student.remove(student.size()-1);
display(student);
System.out.println("2nd element of arraylist" +student.get(1));
display(student);
student.add(0,"Muhammad Walled");
display(student);
student.clear();
display(student);
}
public static void display(ArrayList<String> student)
{
for(String x:student)
{
System.out.println(x);
}
System.out.println();
}}
Output:
} ------------------------------------------------------------------------------------------------------------
0 Comments