Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...