Results 1 to 3 of 3
  1. #1
    tribujohn is offline Member
    Join Date
    Jan 2009
    Rep Power

    Default How to add coins in ascending order in arraylist

    Hey guys I am having a prob adding coins in an ascending order in an arraylist. There are three classes: coins that declare the value and the name of the coins; the purse class that implements the methods and a tester.

    Here is the method where I have a problem:

    public void add(Coin aCoin) {

    Coin temp;
    Coin current;
    for (int i = 0; i < coins.size(); i++) {
    current = (Coin) coins.get(i);
    if (current.getValue() > aCoin.getValue()) {
    coins.set(i, aCoin);

    for (int j = i + 1; j < (coins.size()) - 1; j++) {
    temp = (Coin) coins.get(j);
    coins.set(j, current);


  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Blog Entries
    Rep Power


    I'm not sure if this is cheating or not, but you could have the Coin class implement the generic Comparable<Coin> interface and then use the Coin's value to do comparisons. Then all you'd have to do would be to add all the Coins to the collection (order and position don't matter!), and when done, call Collections.sort(coins); and your list is sorted.

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Colombo, Sri Lanka
    Blog Entries
    Rep Power

Similar Threads

  1. Sorting in descending order
    By santanu in forum New To Java
    Replies: 6
    Last Post: 11-26-2008, 11:43 PM
  2. Descending order
    By santanu in forum New To Java
    Replies: 1
    Last Post: 11-04-2008, 04:33 PM
  3. Replies: 5
    Last Post: 06-06-2008, 09:31 AM
  4. Tab order on swing components
    By in forum AWT / Swing
    Replies: 1
    Last Post: 05-31-2008, 10:06 AM
  5. Replies: 2
    Last Post: 04-21-2008, 11:43 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts