355,490 views
4 votes
4 votes
Write the following generic method that sorts an ArrayList of Comparable items. The sort method must use the compareTo method.

public static > void sort(ArrayList list)
Write a test program that:
1. prompts the user to enter 10 integers, invokes this method to sort the numbers, and displays the numbers in ascending order
2. prompts the user to enter 5 strings, invokes this method to sort the strings, and displays the strings in ascending (alphabetical) order

User Alexander Pozdneev
by
2.9k points

1 Answer

19 votes
19 votes

Answer:

Step-by-step explanation:

The following code is written in Java, it prompts the user to enter 10 integers and saves them to an ArrayList. Then it prompts for 5 strings and saves them to another ArrayList. Then, it calls the sort method and adds the lists as parameters. Finally, it prints out both lists completely sorted in ascending order.

import java.util.ArrayList;

import java.util.Scanner;

class Division{

public static double division(double a, double b) throws Exception {

if(b == 0)

//throw new Exception("Invalid number.");

return (a / b);

return a / b;

}

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

ArrayList<Integer> mylist2 = new ArrayList<>();

for (int x = 0; x < 10; x++) {

System.out.println("Please Enter a Number: ");

int number = in.nextInt();

mylist2.add(number);

}

ArrayList<String> mylist = new ArrayList<>();

for (int x = 0; x < 5; x++) {

System.out.println("Please Enter a Word: ");

String word = in.nextLine();

mylist.add(word);

}

sort(mylist);

sort(mylist2);

for (String x: mylist) {

System.out.print(x + ", ");

}

System.out.println("");

for (int x: mylist2) {

System.out.print(x + ", ");

}

}

public static <E extends Comparable<E>> ArrayList<E> sort(ArrayList<E> list) {

E temp;

if (list.size()>1) // check if the number of orders is larger than 1

{

for (int x=0; x<list.size(); x++) // bubble sort outer loop

{

for (int i=0; i < list.size() - x - 1; i++) {

if (list.get(i).compareTo(list.get(i+1)) > 0)

{

temp = list.get(i);

list.set(i,list.get(i+1) );

list.set(i+1, temp);

}

}

}

}

return list;

}}

Write the following generic method that sorts an ArrayList of Comparable items. The-example-1
User Andrew Smith
by
2.7k points