优化此ArrayList连接方法 [英] Optimize this ArrayList join method

查看:187
本文介绍了优化此ArrayList连接方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已编写此代码以连接ArrayList元素:
可以更优化吗?或者有更好的不同方式吗?

I have written this code to join ArrayList elements: Can it be optimized more? Or is there a better different way doing this?

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();
    }


推荐答案

这里是着名的java.util.Collection团队如何做到这一点,所以我认为这应该是相当不错的;)

Here is how the famous java.util.Collection team are doing it, so I'd assume this should be pretty good ;)

  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的答案得到逗号分隔符的方法; )

Also, this is how you'll get comma delimiters with duffymo's answer ;)

这篇关于优化此ArrayList连接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆