[ISSUE #6198] BUG nacos-common>utils>StringUtils.join method NullPointerException #6198 (#6213)

* [ISSUE #6198] fix bug

* format code

* Modify Comment.Remove toString()
This commit is contained in:
ZZQ的 2021-06-30 19:13:40 +08:00 committed by GitHub
parent 5bb048cf7a
commit 4cd6c58a95
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 56 additions and 10 deletions

View File

@ -125,11 +125,12 @@ public class StringUtils {
}
/**
* Join object with input separator.
* <p>Joins the elements of the provided array into a single String
* containing the provided list of elements.</p>
*
* @param collection collection of objects need to join
* @param separator separator
* @return joined string
* @param collection the Collection of values to join together, may be null
* @param separator the separator string to use
* @return the joined String, {@code null} if null array input
*/
public static String join(Collection collection, String separator) {
if (collection == null) {
@ -139,12 +140,15 @@ public class StringUtils {
StringBuilder stringBuilder = new StringBuilder();
Object[] objects = collection.toArray();
for (int i = 0; i < collection.size() - 1; i++) {
stringBuilder.append(objects[i].toString()).append(separator);
}
if (collection.size() > 0) {
stringBuilder.append(objects[collection.size() - 1]);
for (int i = 0; i < collection.size(); i++) {
if (objects[i] != null) {
stringBuilder.append(objects[i]);
if (i != collection.size() - 1 && separator != null) {
if (separator != null) {
stringBuilder.append(separator);
}
}
}
}
return stringBuilder.toString();

View File

@ -0,0 +1,42 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common.utils;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
/**
* String utils.
* @author zzq
*/
public class StringUtilsTest {
@Test
public void testJoin() {
ArrayList<Object> objects = new ArrayList<>();
objects.add(null);
Assert.assertNull(StringUtils.join(null, "a"));
Assert.assertEquals(StringUtils.EMPTY, StringUtils.join(Arrays.asList(), "a"));
Assert.assertEquals(StringUtils.EMPTY, StringUtils.join(objects, "a"));
Assert.assertEquals("a;b;c", StringUtils.join(Arrays.asList("a", "b", "c"), ";"));
Assert.assertEquals("abc", StringUtils.join(Arrays.asList("a", "b", "c"), null));
}
}