AJW AJW -3 years ago 100
Java Question

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.

Answer Source

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());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download