Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to assign to String[] from StringBuffer in a loop?

Status
Not open for further replies.

navrsalemile

Programmer
Feb 6, 2005
62
0
0
CA
Hi all,


public class Test {
public String[] getSJ()
{
String[] jg;
String[] jig;

String[] result;

StringBuffer buf = new StringBuffer();
int i;
int j;
int k = -1;

jg = {"g1", "g2"};

for( i=0; i < jg.length; i++ )
{
jig = {"1", "2", "3"};
for( j=0; i < jig.length; j++, k++ )
{
buf.append( jg ).append( ":" );
buf.append( jig[j] ).append( ":" );
buf.append( Date() );
result[k] = buf.toString();
buf = null;
}
}
return result;
}
}



I want to add to result string array by assigning from buf which is StringBuffer in a loop. But what happens after buf = null??
Will the added String be gone?

Or should I just do:

buf = "";

and continue with the loop and the string objects will be preserved? But isn't result just an array of references?

Many thanks,
 
I'm confused here ...
Why are you bothering to set your StringBuffer to null ?
That will just cause a big NullPointerException.
Also, you use the variable 'k' to -1, and then assign a subscript of the 'result' array at position -1 - which will cause a big IndexOutOfBoundsException ...

Also, please post code, correctly indented, within the tags [ignore]
Code:
[/ignore]
.


--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
And a performance tip:

If you set an initial size for the StringBuffer a little bigger than the expected final size, the concatenatios will be much quicker.

Maybe won't make a big difference for a three iterations loop, but can do if the loop grows.

Cheers,
Dian
 
Defining all variables at the beginning of a function was c-Style in former times, wasn't it?
In java you introduce them just in time, to the smallest scope possible.

Code:
	public String [] getSJ ()
	{
		String [] result = new String [6];
		String [] jg = {"g1", "g2"};
		int k = 0;
		for (int i=0; i < jg.length; i++ )
		{
			String [] jig = {"1", "2", "3"};

			for (int j=0; j < jig.length; j++, k++ )
			{
				StringBuffer buf = new StringBuffer ();
				buf.append ( jg [i] ).append ( ":" );
				buf.append ( jig [j] ).append ( ":" );
				buf.append ( new Date () );
				result [k] = buf.toString ();
			}
		}
		return result;
	}

seeking a job as java-programmer in Berlin:
 
I don't agree. You should not declare variables inside a loop, that would need an objet allocation per iteration.

I'd go this way:

Code:
    public String [] getSJ ()
    {
        String [] result = new String [6];
        String [] jg = {"g1", "g2"};
        StringBuffer buf = null;
        String [] jig = {"1", "2", "3"};

        for (int i=0; i < jg.length; i++ )
        {
            for (int j=0; j < jig.length; j++)
            {
                buf = new StringBuffer (100);
                buf.append ( jg [i] ).append ( ":" );
                buf.append ( jig [j] ).append ( ":" );
                buf.append ( new Date () );
                result [3*i+j] = buf.toString ();
            }
        }
        return result;
    }

Cheers,
Dian
 
As the matter of fact this appears to be correct solution (in the example I use limited number of items but it should be dynamically allocated):

Code:
import java.util.*;

public class Test {

	public void Test() {
	}

public String[] getSJ()
    {
        String[] jg = {"g1", "g2"};    //can be unlimited
        String[] jig = {"1", "2", "3"};//ditto
		
	String[]     result = new String[0];

	ArrayList al = new ArrayList();

        StringBuffer buf = new StringBuffer();
        int i;
        int j;
        int k = 0;

for( i=0; i < jg.length; i++ )
        {
         for( j=0; j < jig.length; j++, k++ )
            {
               buf.append( jg[i] )
                  .append( ":" )
                  .append( jig[j] )
                  .append( ":" )
                  .append( new Date() );
               
	       al.add( buf.toString() );
               buf.setLength(0);
            }
    }
    return( (String[])al.toArray(result) );
  }

 public static void main( String[] args ) {
    Test   t = new Test();
    String[] res = t.getSJ();
    for( int i=0; i<res.length; i++ ) {
	System.out.println( res[i] );
    }
 }
}

Does anybody know how to do it without help of containers, i.e. just using Array? I read somewhere about varargs in Java but forgot how to do it
 
@diancecht:
I don't agree. You should not declare variables inside a loop, that would need an objet allocation per iteration.
I can't agree.
A declaration doesn't leed to object allocation, but calling<i> new</i> does.

You don't save anything in the case of 'buf'.
You do save the time for creating jig.
In a loop which is run twice.
I'm impressed.

But you allocate a StringBuffer of size 100 instead of 34.

seeking a job as java-programmer in Berlin:
 
@stefan

You're right, I was thinking in another thing: the declaration of the buf variable is irrelevant, but

- Since you cannot know neither how many times the loop will be executed nor the size of the jig array, it's ok to declare it outside.
- Defining a size for the StringBuffer bigger than the expected amount of data saves time on concatenating, since toy don't need to expand the capacity of the buffer again and again
- Glad you're impressed, I'll write it down in my diary.

@salemile.

You could define the result array as jig.size()*jg.size() but I see nothing wrong on using Arraylist.

Is this for an assignment?

Cheers,
Dian


 
No, but I am sure I saw varargs example in Bruce Eckel book Thinking in Java. If I correctly remember in the initializer he puts comma character after the last item which is same as varargs in C/C++
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top