java - How not to display commas at the start and the end of the list -


i have tostring() method. how print [a,b,c,d] instead of [,a,b,c,d,]

  public string tostring()   {     string result = "[";      if (numitems > 0)     {       (int = 0; < queuearray.length && queuearray[i] != null; i++)       {           result+= queuearray[i].tostring() + ",";       }           result += "]";     }     else     {       result = "[ ]";     }      return result;   } 

use stringjoiner:

public string tostring() {     stringjoiner sj = new stringjoiner(","); // use commas attach      if (numitems > 0) {         (int = 0; < queuearray.length && queuearray[i] != null; i++) {             sj.add(queuearray[i].tostring()); // loop through & attach         }         sj.add("]");     } else {         sj.add("[ ]");     }      return sj.tostring(); } 

here sample program, clarify how works:

public static void main(string[] args) {     // pass in "joiner" string stringjoiner's constructor      stringjoiner sj = new stringjoiner("/"); // in case, use slashes      // strings attached     string[] strings = new string[]{"hello", "world", "!"};      (string str : strings)         sj.add(str); // attach      system.out.println(sj.tostring()); // print content of stringjoiner } 

and output is:

hello/world/! // no slash in end 

Comments