Build two simple arrays (Integer and String) of 6 in length. Convert the two arrays into a List type using an ArrayList type. A static method Array2Collection generic method is provided for that. From the List, display the contents of the two arrays in the forward or backward order: (without using an index for loop)
//Code for converting Array to a Collection type
static <T> void Array2Collection(T[] a, Collection<T> c) {
for (T x : a) {
c.add(x); // Correct
}
}
Output:
lint: [0, 1, 3, 5, 7, 9]
list: [Karl, Mike, Arthur, Ray, Sydney, Kayla]
lint: forward order
0 1 3 5 7 9
lint: reverse order
9 7 5 3 1 0
list: forward order
Karl Mike Arthur Ray Sydney Kayla
list: reverse order
Kayla Sydney Ray Arthur Mike Karl
The original lists (lint, list)
lint: [0, 1, 3, 5, 7, 9]
list: [Karl, Mike, Arthur, Ray, Sydney, Kayla]
To solve this question first create two arrays one for storing the integer and other to store the strings. Here two arrays names and integers are created to store the respective values. After that create two empty ArrayList namely n1 and n2 and call the function Array2Collection() as provided in the question to convert the array and add the values to it.
After that In order to print without index-based loop use for each loop to print the content of the ArrayList. The Last step is to reverse the order, So to do that just use Collections.reverse() function which will reverse the ArrayList.
The necessary comments that will help you understand the solution.
import java.util.*;
class Test{
// Conversion method
static <T> void Array2Collection(T[] a, Collection<T> c) {
for (T x : a) {
c.add(x); // Correct
}
}
public static void main(String[] args) {
// Two Arrays
String[] names = {"Karl", "Mike", "Arthur", "Ray", "Sydney", "Kayla"};
Integer[] integers = {0,1,3,5,7,9};
ArrayList<Integer> n1 = new ArrayList<Integer>();
ArrayList<String> n2 = new ArrayList<String>();
Array2Collection(integers, n1);
Array2Collection(names, n2);
ArrayList<Integer> s1 = new ArrayList<Integer>(n1);
ArrayList<String> s2 = new ArrayList<String>(n2);
System.out.println("Lint: " + n1);
System.out.println("list: " + n2);
// Lint Forward and Backward
System.out.println("lint: forward order ");
for(Integer i: n1){
System.out.print(i+ " ");
}
System.out.println();
Collections.reverse(n1);
System.out.println("lint: reverse order ");
for(Integer i: n1){
System.out.print(i+ " ");
}
System.out.println();
// List Forward and BackWard
System.out.println("list: forward order" );
for(String i: n2){
System.out.print(i+ " ");
}
System.out.println();
Collections.reverse(n2);
System.out.println("list: reverse order" );
for(String i: n2){
System.out.print(i+ " ");
}
System.out.println();
// Printing orginal list
System.out.println("The orginal lists(lint,list)");
System.out.println("lint: " + s1);
System.out.println("list: " + s2);
}
}
I hope you have understood
the solution. If you like the solution kindly upvote
it.
Get Answers For Free
Most questions answered within 1 hours.