Chance Smith
Chance Smith

Reputation: 33

Reversing ArrayList<String>

All im trying to do is reverse the ArrayList. Is there a way I could do it through the toString as well or should I just create a method like I did. Im so close, any answers will help! Thanks!

  package edu.purse.test;

  java.util.ArrayList;
  import java.util.Collections;

   public class Purse 
 {
ArrayList<String> coins = new ArrayList<String>();
public Purse()
{

}
public void addCoin(String coinName)
{

    coins.add(coinName);
}
public String toString()
{
    return  "Purse" + coins.toString();
}
public ArrayList<String> getReversed(ArrayList<String> coins) 
{ 
ArrayList<String> copy = new ArrayList<String>(coins); 
Collections.reverse(copy); 
return copy; 
}

 }

TESTERCLASS

    package edu.purse.test;

  import java.util.Collections;
   import java.util.List;

  public class PurseTester {
public static void main(String[] args) {
    Purse p = new Purse();
    p.addCoin("Quarter");
    p.addCoin("Dime");
    p.addCoin("Nickel");
    p.addCoin("Penny");
    System.out.println(p.toString());

    p.getReversed(coins);
}

}

Upvotes: 2

Views: 1863

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280179

The method

p.getReversed(coins);

returns a reversed list. You can just print it out

System.out.println(p.getReversed(coins));

Note that you are getting a copy of your instance's list, reversing that, and then returning it. If you want to preserve the change, simple call Collections.reverse() on the original, coins.

Upvotes: 7

Related Questions