AJW
AJW

Reputation: 5863

reverses in arraylist strings

I am trying to reverse some contents of strings in an arraylist , and I was wondering if this was possible using standard classes [.reverse().toString() in particular]. For example, I have an arraylist with the following entries in them:

    mySuperArray=[the cost of apple is USD2, the cost of oranges are USD1.50]

and what Id want is something which reverses these strings in the above array: like:

    hArray=[2DSU si elppa fo tsoc eht, etc..]

What I am using at the moment is something like:

    ArrayList<String> hArray= new ArrayList<String>();
    hArray = new StringBuffer(mySuperArray).reverse().toString();

where, mySuperArray is defined the same way as hArray.

But I get a compile error at this stage:

    cannot find symbol
    symbol  : constructor StringBuffer(java.util.ArrayList<java.lang.String>)
    location: class java.lang.StringBuffer
    hArray = new StringBuffer(mySuperArray).reverse().toString();

Why do I get this compile error? What could be wrong? Sorry if the question is a rather newbie question.

Upvotes: 0

Views: 236

Answers (3)

Somasundar Kanakaraj
Somasundar Kanakaraj

Reputation: 11

public static void main(String[] args) throws IOException, ParseException, InterruptedException {
        ArrayList<String> obj = new ArrayList<String>();
        obj.add("A");
        obj.add("B");
        obj.add("C");
        obj.add("D");
        obj.add("E");
        System.out.println("Entered :: "+obj);
        for(int i=obj.size()-1; i>=0; --i){
            System.out.println("Values :: "+obj.get(i));
            obj.add(obj.get(i));
            obj.remove(i);
        }
        System.out.println("Reversed :: "+obj);
}

Upvotes: 0

Neo
Neo

Reputation: 1554

The error is that you cannot use a constructor StringBuffer(ArrayList). You can refer to the Java documentation online to see what constructors you can use. http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html (this is Java 1.5). So, the closest constructor you can use is StringBuffer(String).

ArrayList hArray= new ArrayList();
for(String s :mySuperArray){
   hArray.add(new StringBuffer(s).reverse().toString());
}

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160191

There is no StringBuffer constructor that takes an ArrayList--what would it mean?

Create a new list, iterate over the original, adding the reverse of each string to the new list. Alternatively, replace each list item with its reverse. (Not as "functional".)

Upvotes: 2

Related Questions