StringBuilderUtil
Facilitates the use of StringBuilder.
- gist: https://gist.github.com/drafa/d97b2563147a55baadea
- methods:
- append(Object... obj) : StringBuilder -> Allows concatenation of objects to one another, adding at the end of the resulting string
- insert(Object... obj) : StringBuilder -> Allows concatenation of objects to one another, adding at the beginning of the resulting string
/**
* Allows concatenation of objects to one another, adding at the end of the
* resulting string
* see {@link StringBuilder#append(Object) StringBuilder.append(Object obj)}
* @param obj
* @return a <code>StringBuilder</code> with all objects
* @author https://github.com/drafa
*/
public static StringBuilder append(Object... obj) {
if(obj==null) { return new StringBuilder("null"); }
StringBuilder sb = new StringBuilder();
int i=0, l=obj.length;
while(i<l) { sb.append(obj[i++]); }
return sb;
}
/**
* Allows concatenation of objects to one another, adding at the beginning
* of the resulting string
* @see {@link StringBuilder#insert(Object) StringBuilder.insert(Object obj)}
* @param obj
* @return a <code>StringBuilder</code> with all objects
* @author https://github.com/drafa
*/
public static StringBuilder insert(Object... obj) {
if(obj==null) { return new StringBuilder("null"); }
StringBuilder sb = new StringBuilder();
int zero=0, i=zero, l=obj.length;
while(i<l) { sb.insert(zero, obj[i++]); }
return sb;
}
Written by Drafa
Related protips
1 Response
Java 8 also has a static join() method which is much more powerful than your append method (you can e.g. define a delimiter for joining).
But if you're stuck with Java < 8 your implementation is quite nice.
To avoid code duplication, I would suggest that insert calls append with the array reversed, something like:
public static StringBuilder insert(Object... obj) {
List<Object> l = new ArrayList<>(Arrays.asList(obj));
Collections.reverse(l);
return append(l.toArray());
}
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Java
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#