简体   繁体   中英

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);
}

}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM