Page 1 of 1

Task 3: ArrayList import java.util.ArrayList; import java.util.Collections; public class Test { public static void main(

Posted: Wed Apr 27, 2022 3:28 pm
by answerhappygod
Task 3: ArrayList
import java.util.ArrayList;
import java.util.Collections;
public class Test
{
public static void main(String[] args)
{
//create
an arryList of cities
ArrayList<String> cities = ……………………………………….
//Adding
items to the arraylist
cities.add("Abu
Dhabi");
cities.add("Al
Ain");
//Add
also the following cities: Dubai, RAK, Ajman
…………………………………………………………………
//Accessing
an item in the Arraylist
System.out.println(cities.get(1));
System.out.println("----------------------------------");
//looping
through the list using the get(index) method
………………………………………………………………………………………………
//modifying
an element in the item
cities.set(1, "Sharjah");
System.out.println("----------------------------------");
//another
way of looping through the list
for(String x: cities)
System.out.println(x);
//remove
an item
cities.remove(0);
System.out.println("----------------------------------");
//sorting a
list
Collections.sort(cities);
for(String x: cities)
System.out.println(x);
//
Use cities.clear() to remove all the elements
}
}
Task 4: Collections class
public static void main(String[] args)
{
String[] colors =
{"red", "green", "blue"};
ArrayList<String> Colorslist = new ArrayList<>(Arrays.asList(colors));
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
public class Test
{
public static void main(String[] args)
{
Integer[] myNumbers =
{3, 5, 95, 4, 15, 34, 3, 6, 5};
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(myNumbers));
//finding
the maximum
System.out.println("The
maximum is " + Collections.max(list));
//write
a code to the minimum number in myNumbers list
………………………………………………………………………………………………………..
//shuffling
the list
System.out.println("This
is shuffled");
//use
the method shuffle() to shuffle the elements in the list
…………………………………………………………………………………………………………………………………………………
System.out.println(list);
//sorting
the list
System.out.println("This
is sorted");
//use
the method sort() in java.util.Collection to sort
the elements in the list
…………………………………………………………………………………………………………………………………………………
System.out.println(list);
}}