Solved

arrayList toString

Posted on 2007-03-19
25
5,719 Views
Last Modified: 2012-05-05
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,
0
Comment
Question by:Tchuki
  • 8
  • 6
  • 4
  • +4
25 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 18747811
You need to have some way of joining them. You could do

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

You want to remove the '[' and ']'
0
 
LVL 10

Expert Comment

by:Jaax
ID: 18747832
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
 
LVL 6

Expert Comment

by:SamsonChung
ID: 18747882
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
 
LVL 14

Author Comment

by:Tchuki
ID: 18747940
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 18747959
>> 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
 
LVL 14

Author Comment

by:Tchuki
ID: 18747973
Its the code above but replacing :

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

with:

tempString = theFile.toString().replaceAll("[", "");
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 18747988
String newText = new StringBuilder(arrayList.toString().replaceAll(",", " ")).deleteCharAt(newText.length() - 1).deleteCharAt(0).toString();
0
 
LVL 35

Expert Comment

by:TimYates
ID: 18748102
StringBuffer sb = new StringBuffer() ;
for( String s : arrayList )
  sb.append( s ) ;

I'm probably missing the point though... ;-)
0
 
LVL 35

Accepted Solution

by:
TimYates earned 500 total points
ID: 18748108
Sorry:

StringBuffer sb = new StringBuffer() ;
for( String s : arrayList )
  sb.append( s ).append( " " ) ;
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18750262
What was the exception you got and could you print its stack trace?
0
 
LVL 14

Author Comment

by:Tchuki
ID: 18750852
I went about it a different way in the end.  Used a string buffer.
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18750862
You can also try StringBuilder if you are using Java 5.0 or 6.0
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 86

Expert Comment

by:CEHJ
ID: 18750868
StringBuilder is to be preferred over StringBuffer if you can use it
0
 
LVL 35

Expert Comment

by:TimYates
ID: 18750877
>> 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
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18750903
Looks like ;)
0
 
LVL 14

Author Comment

by:Tchuki
ID: 18750975
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
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18751156
>> theFile.set(i, "REPLACED");

Should this not be done after: >> obj = theFile.get(i);
0
 
LVL 14

Author Comment

by:Tchuki
ID: 18751240
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
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18751349
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
 
LVL 14

Author Comment

by:Tchuki
ID: 18751373
yes.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 18751540
Not sure I deserved all the points here...
0
 
LVL 14

Author Comment

by:Tchuki
ID: 18751614
Well I went with your solution ... ?  :P
0
 
LVL 30

Expert Comment

by:mayankeagle
ID: 18753522
What is the output you expect and what is the output you get?
0
 
LVL 14

Author Comment

by:Tchuki
ID: 18754537
It's cool, I resolved the issue using the StringBuilder method.
0
 

Expert Comment

by:worklogix
ID: 23132592

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

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
word0 challenge 4 54
bitbucket vs gitbucket 3 34
eclipse compiler vs Installed JREs option 3 42
github account with ecipse 1 20
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now