gpt4 book ai didi

java - 优化这个ArrayList的join方法

转载 作者:行者123 更新时间:2023-11-29 10:07:52 26 4
gpt4 key购买 nike

我编写了这段代码来连接 ArrayList 元素:能再优化一下吗?或者有更好的不同方法吗?

public static String join(ArrayList list, char delim) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
if (i != 0)
buf.append(delim);
buf.append((String) list.get(i));
}
return buf.toString();
}

最佳答案

Here著名的 java.util.Collection 团队就是这样做的,所以我认为这应该非常好 ;)

  421       /* Returns a string representation of this collection.  The string
422 * representation consists of a list of the collection's elements in the
423 * order they are returned by its iterator, enclosed in square brackets
424 * (<tt>"[]"</tt>). Adjacent elements are separated by the characters
425 * <tt>", "</tt> (comma and space). Elements are converted to strings as
426 * by {@link String#valueOf(Object)}.
427 *
428 * @return a string representation of this collection
429 */
430 public String toString() {
431 Iterator<E> i = iterator();
432 if (! i.hasNext())
433 return "[]";
434
435 StringBuilder sb = new StringBuilder();
436 sb.append('[');
437 for (;;) {
438 E e = i.next();
439 sb.append(e == this ? "(this Collection)" : e);
440 if (! i.hasNext())
441 return sb.append(']').toString();
442 sb.append(", ");
443 }

此外,这就是您将如何使用 duffymo 的答案获得逗号分隔符;)

关于java - 优化这个ArrayList的join方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2389448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com