0

I am currently using an Iterator to output an array list but I want to output it all on one line. I think my best bet would be to use a stringbuffer but does anyone have a more effective method?

My current method of output is this:

Iterator itr = cards.iterator();
while(itr.hasNext()){
    System.out.println(itr.next());
    System.out.println(); 
}

Went with this Not efficient at all but its all I understand at the moment:

 Iterator itr = cards.iterator();
 String str = "";
    while(itr.hasNext()){
        str += (itr.next() + ", ");
    }
    return str;
0

4 Answers 4

2

Use System.out.print() instead of System.out.println().

See PrintStream

Sign up to request clarification or add additional context in comments.

Comments

1

Use Arrays#toString to convert an array into a String, like so:

final String string = Arrays.toString( myArray );
System.out.println( string ); 

1 Comment

So I am getting an error about this line. final String string = Array.toString(cards);
0

You can use the System.out.print() method, it doesn't change the line.

But I recommend to use a more efficient method, like the StringBuffer that you had suggest.

1 Comment

It is debatable if it is more efficient. Sure StringBuffer is more efficient in some situations (and no doubt more flexible in general), but this is not the case IMHO.
0

You should make some search on stackoverflow. I think there are some good solutions for your problem. For example check this: Java: StringBuffer & Concatenation

You should solve the problem like this:

public String myMethod() {
    StringBuilder sb = new StringBuilder();

    Iterator itr = cards.iterator();
    while(itr.hasNext()){
        addToBuffer(sb, itr.next());
    }
    return sb.toString();
}

private void addToBuffer(StringBuilder sb, String what) {
    sb.append(what).append(' ');  // char is even faster here! ;)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.