arrayList toString

I have an arrayList which is populated from a text file.

I then change certain arrayList index elements .remove() and .add(i, newString).  At the end of that I am still left with an arrayList.

What I am looking to do is turn that arrayList back into a string so it can be displayed on screen in a JTextArea before being saved back to a text file.

I did try:

String str = arrayList.toString();
jtextAreaOutput.setText(str);

But that produced:

[element1, element2, etc]

How can this be resolved ?

Thanks,
LVL 14
Vel EousResearch & Development ManagerAsked:
Who is Participating?
 
TimYatesConnect With a Mentor Commented:
Sorry:

StringBuffer sb = new StringBuffer() ;
for( String s : arrayList )
  sb.append( s ).append( " " ) ;
0
 
CEHJCommented:
You need to have some way of joining them. You could do

ta.setText(arrayList.toString().replaceAll(",", " ");

You want to remove the '[' and ']'
0
 
JaaxArchitectCommented:
It all depends on what format you wish to display the contained elements. Seems like you are  not satisfied with the default implementation of  ArrayList. All you have to do is iterate over the list and format the retrieved elements.
For eg, if you need to display the strings as CSV
String csv = "";
for(int i=0; i < list.size();i++){
   csv += (String)list.get(i)+",";
}
if(csv.length() > 1){
 csv += csv.substring(0, csv.length());
}
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
SamsonChungCommented:
try overloading the ArrayList's toString() method.

if you have edited remove(), add(), etc, try to look for a toString()

If none, then simply write one in the class.

0
 
Vel EousResearch & Development ManagerAuthor Commented:
OK, I attemped what you said:

public void find() {
            
            String find = Jaypad.searchString;
            String tempString = null;
            int x = theFile.size();
            
            for (int i=0; i<(x); i++) {
                  if (theFile.get(i).equals(find)) {
                        theFile.remove(i);
                        theFile.add(i, "REPLACED");
                        tempString = theFile.toString().replaceAll(",", "");
                        System.out.println(tempString);
                        
                  } else {
                        Jaypad.jlblStatus.setText("Not found");
                  }
            }
            Jaypad.jtextAreaDisplay.setText(tempString);
            Jaypad.jlblStatus.setText(find);
      }

^^ works fine, removes the "," from between array elements.  When I attempt to replace all "[" or "]" symbols though, I get a runtime error.
0
 
CEHJCommented:
>> When I attempt to replace all "[" or "]" symbols though, I get a runtime error.

It's just a simple substring operation. Can you post the code you tried?
0
 
Vel EousResearch & Development ManagerAuthor Commented:
Its the code above but replacing :

tempString = theFile.toString().replaceAll(",", "");

with:

tempString = theFile.toString().replaceAll("[", "");
0
 
CEHJCommented:
String newText = new StringBuilder(arrayList.toString().replaceAll(",", " ")).deleteCharAt(newText.length() - 1).deleteCharAt(0).toString();
0
 
TimYatesCommented:
StringBuffer sb = new StringBuffer() ;
for( String s : arrayList )
  sb.append( s ) ;

I'm probably missing the point though... ;-)
0
 
Mayank SAssociate Director - Product EngineeringCommented:
What was the exception you got and could you print its stack trace?
0
 
Vel EousResearch & Development ManagerAuthor Commented:
I went about it a different way in the end.  Used a string buffer.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
You can also try StringBuilder if you are using Java 5.0 or 6.0
0
 
CEHJCommented:
StringBuilder is to be preferred over StringBuffer if you can use it
0
 
TimYatesCommented:
>> I went about it a different way in the end.  Used a string buffer.

My example used a StringBuffer...  Did you go that way then?
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Looks like ;)
0
 
Vel EousResearch & Development ManagerAuthor Commented:
Sorry, not feeling well and I`m not taking things in very well at the moment.  I've ended up with the following which outputs the arrayList minus all that array stuff ( [ , ] etc ):


// search & replace all method
      public void findAndReplaceAll() {
            
            String find = Jaypad.searchString;
            int x = theFile.size();
            
            Object obj = null;
            StringBuilder strBuild = new StringBuilder();
            
            for (int i=0; i<x; i++) {
                  if (theFile.get(i).equalsIgnoreCase(find)) {
                        theFile.set(i, "REPLACED");
                        System.out.println(theFile);
                        obj = theFile.get(i);
                        strBuild.append(obj + " ");
                  } else {
                        obj = theFile.get(i);
                        strBuild.append(obj + " ");
                  }
            }
            String result = strBuild.toString();
            Jaypad.jtextAreaDisplay.setText(result);
      }

Thing is my array appears to be skipping over elements that match my search criteria.  :/
0
 
Mayank SAssociate Director - Product EngineeringCommented:
>> theFile.set(i, "REPLACED");

Should this not be done after: >> obj = theFile.get(i);
0
 
Vel EousResearch & Development ManagerAuthor Commented:
Why though ?

I want to replace the element, then send the new element to the StringBuilder.  If put obj = theFile.get(i); before I replace the element I`m just sending the old element to the StringBuilder am I not ?
0
 
Mayank SAssociate Director - Product EngineeringCommented:
I thought you wanted to append the old ones, sorry. But in your code, the new element is always the String "REPLACED" right? 'theFile' is the ArrayList?
0
 
Vel EousResearch & Development ManagerAuthor Commented:
yes.
0
 
TimYatesCommented:
Not sure I deserved all the points here...
0
 
Vel EousResearch & Development ManagerAuthor Commented:
Well I went with your solution ... ?  :P
0
 
Mayank SAssociate Director - Product EngineeringCommented:
What is the output you expect and what is the output you get?
0
 
Vel EousResearch & Development ManagerAuthor Commented:
It's cool, I resolved the issue using the StringBuilder method.
0
 
worklogixCommented:

arrayList.toString().replace('[',' ').replace(']',' ').replaceAll(" ","")

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.