As you know, the toString() method called on a Vector output this
[foo, bar, item, item4]
This is pretty basic but, how could I get this instead (removing white spaces between elements)?
[foo,bar,item,item4]
Thank you all
EDIT: return nom.toString().replace(" ", ""); is not a solution !
Use replace () function to replace all the space characters with a blank. The resulting string will not have any spaces in-between them.
By overriding the toString( ) method, we are customizing the string representation of the object rather than just printing the default implementation. We can get our desired output depending on the implementation, and the object values can be returned.
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
When you print an object, by default the Java compiler invokes the toString() method on the object. So by overriding the toString() method, we can provide meaningful output.
Wrap your vector class and override toString.
import java.util.*;
class AwesomeVector<E> extends Vector<E> {
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i = 0; i < size(); i++) {
if(i != 0) sb.append(",");
sb.append(get(i));
}
sb.append("]");
return sb.toString();
}
public static void main(String[] args) {
AwesomeVector<String> av = new AwesomeVector<String>();
av.add("This");
av.add("is");
av.add("a test");
System.out.println(av.toString());
}
}
C:\Documents and Settings\glowcoder\My Documents>javac AwesomeVector.java
C:\Documents and Settings\glowcoder\My Documents>java AwesomeVector
[This,is,a test]
Overriding only makes sense if you are subclassing Vector
.
If you are, then you can use Apache Commons Lang's StringUtils.join as follows:
@Override
public String toString() {
return "[" + StringUtils.join(this, ",") + "]";
}
If you want to stay in plain Java, glowcoder has the best answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With