HashSet中的多余逗号 [英] Extra comma in HashSet

查看:40
本文介绍了HashSet中的多余逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用大写字母拆分字符串,例如,当字符串为"SizeColorSize"时,输出数组为:{"Size","Color","Size"}.这正常工作.现在,我想从数组中删除重复项,这就是为什么我使用HashSet的原因,这样我将获得["Color","Size"]排序的集合.然后我将输出打印在MySQL表中.

I'm trying to split strings by capital letters, for example when the string is "SizeColorSize", the aoutput array is: {"Size", "Color", "Size"}. This works normally. Now I want to remove the duplicates from the array and that's why I am using HashSet, so that I would have ["Color", "Size"] sorted collection. Then I am printing the output in MySQL table.

但是问题是在输出中我还有一个逗号:[,"Color","Size"].知道为什么会这样吗?

But the problem is that in the output I have one extra comma : [, "Color", "Size"]. Any idea why is it like that?

这是代码的一部分:

for (int j = 0; j < configPair.size(); j++) {
    r = configPair.get(j).split("(?=\\p{Lu})");
    for (int i = 0; i < r.length; i++) {
        r = new HashSet<String>(Arrays.asList(r)).toArray(new String[0]);
        r[i].trim();
        Arrays.sort(r);
        Set<String> mySet = new HashSet<String>(Arrays.asList(r));
        sqlAttributeConfig = "INSERT INTO Config_Attributes (Config_Pairs) VALUES ('"
                    + mySet + "')";
        System.out.print(r[i]);             
    }
    System.out.println();
    r = null;
    con.stmt.executeUpdate(sqlAttributeConfig);
}

推荐答案

String 的开头与 String.split()中的正则表达式模式匹配时,结果为在另一个空的 String 中.

When the beginning of a String matches the regex pattern in String.split(), it results in an additional empty String.

因此, split 将返回[","Size","Color","Size"]而不是["Size","Color","Size],因此行为

So the split will return you ["", "Size", "Color", "Size"] instead of ["Size", "Color", "Size], thus the behavior.

Split的官方Javadoc说:

The official Javadoc of Split said the following:

此方法返回的数组包含输入的每个子字符串由与此匹配的另一个子序列终止的序列模式或在输入序列的结尾处终止.

The array returned by this method contains each substring of the input sequence that is terminated by another subsequence that matches this pattern or is terminated by the end of the input sequence.

因此,我猜想前导的空 String 会被视为输入序列的子字符串,该子字符串由与该模式匹配的另一个子序列终止",如文档中所述.

So I guess the leading empty String qualifies as a "substring of the input sequence that is terminated by another subsequence that matches this pattern", as said in the doc.

这篇关于HashSet中的多余逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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