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;

4 Answers4

2

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

See PrintStream

Nate W.
  • 9,141
  • 6
  • 43
  • 65
Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
1

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

final String string = Arrays.toString( myArray );
System.out.println( string ); 
Nate W.
  • 9,141
  • 6
  • 43
  • 65
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.

Nettogrof
  • 2,116
  • 2
  • 15
  • 22
  • 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. – DejanLekic Nov 09 '11 at 23:40
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! ;)
}
Community
  • 1
  • 1
emin
  • 742
  • 9
  • 21