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

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

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

Post 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);
}}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply