StringBuilder的一个坑

今天在使用StringBuilder时,当传入参数类型为char时,会调用如下构造方法

/**
     * Constructs a string builder with no characters in it and an
     * initial capacity specified by the {@code capacity} argument.
     *
     * @param      capacity  the initial capacity.
     * @throws     NegativeArraySizeException  if the {@code capacity}
     *               argument is less than {@code 0}.
     */
    public StringBuilder(int capacity) {
        super(capacity);
    }

此时char类型被转成了其ASCII码所对应的int值,并且被当成了初始容量,想要将char作为 值 而非 初始容量 传入,可参考如下方法

char ch = 'A';
StringBuilder sb = new StringBuilder(String.valueOf(ch));

ok,就一个小坑

posted @ 2022-03-01 11:45  雨下_整夜  阅读(55)  评论(0编辑  收藏  举报