Solved

arrayList toString

Posted on 2007-03-19
25
5,720 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:Mayank S
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:Mayank S
ID: 18750862
You can also try StringBuilder if you are using Java 5.0 or 6.0
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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:Mayank S
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:Mayank S
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:Mayank S
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:Mayank S
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Modeling a class in java 5 46
Problem to start Neon 20 84
starter POM and spring-boot-starter,  spring-boot-web 2 40
diffSum example 4 21
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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 will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

919 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