[Conceptos básicos de Java] Calcule la longitud total de la matriz en la matriz de cadenas (StringUtils.join y StringBuilder.append)

Prefacio

Recientemente, cuando estaba desarrollando, necesitaba calcular la longitud de una matriz de cadenas después del empalme. Originalmente planeé escribir una clase de herramienta simple para calcular la longitud. Después de que un colega me lo recordó, descubrí que existe una herramienta tan útil. clase
.


método uno

    public static int calculateStrJoinLengthOfListMethod1(List<String> strList){
    
    
        if(CollectionUtils.isEmpty(strList)){
    
    
            return 0;
        }
        // 数组的join方法 “[Hello,world,abc]”
        String tmpStr1 = StringUtils.join(strList);

        // 注意此处我们不希望使用默认的分隔符 "," "HelloWorldAbc"
        String tmpStr2 = StringUtils.join(strList, "");
        return tmpStr2.length();
    }

Método dos

    public static int calculateStrJoinLengthOfListMethod2(List<String> strList){
    
    
        if(CollectionUtils.isEmpty(strList)){
    
    
            return 0;
        }
        StringBuilder builder = new StringBuilder();
        strList.forEach(str -> builder.append(str));
        return builder.toString().length();
    }

Métodos de prueba

package com.yanxml.util.string;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;


public class StringArrayUtils {
    
    

    public static int calculateStrJoinLengthOfListMethod1(List<String> strList){
    
    
        if(CollectionUtils.isEmpty(strList)){
    
    
            return 0;
        }
        // 数组的join方法 “[Hello,world,abc]”
        String tmpStr1 = StringUtils.join(strList);

        // 注意此处我们不希望使用默认的分隔符 "," "HelloWorldAbc"
        String tmpStr2 = StringUtils.join(strList, "");
        return tmpStr2.length();
    }


    public static int calculateStrJoinLengthOfListMethod2(List<String> strList){
    
    
        if(CollectionUtils.isEmpty(strList)){
    
    
            return 0;
        }
        StringBuilder builder = new StringBuilder();
        strList.forEach(str -> builder.append(str));
        return builder.toString().length();
    }

    public static void main(String[] args) {
    
    
        List<String> strList = new ArrayList<>();
        strList.add("Hello");
        strList.add("World");
        strList.add("abc");

        // 测试方法1
        int lengthByTest1 = calculateStrJoinLengthOfListMethod1(strList);
        System.out.println("Test By Method1 - StringUtils.join, length " + lengthByTest1);

        // 测试方法2
        int lengthByTest2 = calculateStrJoinLengthOfListMethod2(strList);
        System.out.println("Test By Method2 - StringBuilder.append, length "+ lengthByTest2);  

    }
}
# 测试结果

Test By Method1 - StringUtils.join, length 13
Test By Method2 - StringBuilder.append, length 13

Análisis de código fuente

Desde la perspectiva del usuario, normalmente debería terminar aquí, pero a partir del desarrollo real, todos hemos aprendido que cuando encontramos problemas, si profundizamos, tendremos una mejor comprensión y recompensas
.

Primero echemos un vistazo más de cerca al método StringUtils.join.

Método de unión de matriz
 String tmpStr1 = StringUtils.join(strList);
# org.apache.commons.lang3.StringUtils 类

	# 单参数重载方法 Array
	public static <T> String join(T... elements) {
    
    
		return join((Object[])elements, (String)null);
	}
	
	# 2个参数重载方法 Array & 间隔符
    public static String join(Object[] array, String separator) {
    
    
        return array == null ? null : join(array, separator, 0, array.length);
    }


	# 4个参数重载方法 Array & 间隔符 & 开始下标 & 结束下标
    public static String join(Object[] array, String separator, int startIndex, int endIndex) {
    
    
        if (array == null) {
    
    
            return null;
        } else {
    
    
            if (separator == null) {
    
    
                separator = "";
            }

            int noOfItems = endIndex - startIndex;
            if (noOfItems <= 0) {
    
    
                return "";
            } else {
    
    
                StringBuilder buf = new StringBuilder(noOfItems * 16);

                for(int i = startIndex; i < endIndex; ++i) {
    
    
                    if (i > startIndex) {
    
    
                        buf.append(separator);
                    }

                    if (array[i] != null) {
    
    
                        buf.append(array[i]);
                    }
                }

                return buf.toString();
            }
        }
    }
  • Como puede ver, este método de unión es el mismo que los dos métodos. El método utilizado StringBuilder.appendes solo una capa de embalaje y no tiene ningún otro uso. Y ambos no son seguros para subprocesos.

Método de unión de cadena
        String tmpStr2 = StringUtils.join(strList, "");
# org.apache.commons.lang3.StringUtilspublic static String join(Iterable<?> iterable, String separator) {
    
    
        return iterable == null ? null : join(iterable.iterator(), separator);
    }
    public static String join(Iterator<?> iterator, String separator) {
    
    
        if (iterator == null) {
    
    
            return null;
        } else if (!iterator.hasNext()) {
    
    
            return "";
        } else {
    
    
            Object first = iterator.next();
            if (!iterator.hasNext()) {
    
    
                String result = ObjectUtils.toString(first);
                return result;
            } else {
    
    
                StringBuilder buf = new StringBuilder(256);
                if (first != null) {
    
    
                    buf.append(first);
                }

                while(iterator.hasNext()) {
    
    
                    if (separator != null) {
    
    
                        buf.append(separator);
                    }

                    Object obj = iterator.next();
                    if (obj != null) {
    
    
                        buf.append(obj);
                    }
                }

                return buf.toString();
            }
        }
    }
  • Lo que es más interesante es que los resultados obtenidos por estos dos métodos son completamente diferentes, el principal problema puede estar aquí, la iteración de la matriz se realiza mediante una conversión forzada y la cadena se procesa return join((Object[])elements, (String)null);usando Iterator.

un extraño fenómeno

El resultado es "[Hola, mundo, Abc]"

        // 数组的join方法 “[Hello,world,abc]”
        String tmpStr1 = StringUtils.join(strList);
        // 注意此处我们不希望使用默认的分隔符 "," "HelloWorldAbc"
        String tmpStr2 = StringUtils.join(strList, "");
  • Puede ser que el primer método de llamada haya activado el método de matriz , lo que provocó que esta pantalla toStringapareciera aquí .[XX,XX,XX]

Referencia

[1] [Método y uso del método StringUtils.join()] ( https://www.cnblogs.com/fenghh/p/12175368.html )
[2] [A qué paquete pertenece CollectionUtils] https:// blog.csdn.net/weixin_42114097/article/details/90579980

Supongo que te gusta

Origin blog.csdn.net/u010416101/article/details/123038426
Recomendado
Clasificación