Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

java - Extra comma in HashSet

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.

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

This is the part of the code:

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...