Question: Write a program that sorts an ArrayList in decreasing order so that the most valuable coin is at the beginning of the array. Use a

Write a program that sorts an ArrayList in decreasing order so that the most valuable coin is at the beginning of the array. Use a Comparator.

You need to supply the following class in your solution:

ReverseCoinComparator 

Use the following class in your solution:

/** A coin with a monetary value. */ public class Coin { private double value; private String name; /** Constructs a coin. @param aValue the monetary value of the coin. @param aName the name of the coin */ public Coin(double aValue, String aName) { value = aValue; name = aName; } /** Gets the coin value. @return the value */ public double getValue() { return value; } /** Gets the coin name. @return the name */ public String getName() { return name; } public String toString() { return "Coin[value=" + value + ",name=" + name + "]"; } } 

Use the following class as your tester class:

import java.util.Collections; import java.util.Comparator; import java.util.ArrayList; /** This program tests sorting an array list of coins. */ public class CoinSortTester { public static void main(String[] args) { ArrayList a = new ArrayList(); a.add(new Coin(0.05, "Nickel")); a.add(new Coin(0.05, "Nickel")); a.add(new Coin(0.25, "Quarter")); a.add(new Coin(0.01, "Penny")); a.add(new Coin(0.1, "Dime")); Comparator comp = new ReverseCoinComparator(); Collections.sort(a, comp); System.out.println(a); System.out.println("Expected: [Coin[value=0.25,name=Quarter], Coin[value=0.1,name=Dime], Coin[value=0.05,name=Nickel], Coin[value=0.05,name=Nickel], Coin[value=0.01,name=Penny]]"); } } 

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!