为什么在SortedSet中查找headSet时要添加空字符"\0"?

4
这个惯用语是什么意思?一个被"\0"连接的Java字符串(例如 "Japan\0")?就像这样:
SortedSet<String> countryHeadSet 
    = countrySet.headSet("Japan\0");

这个调用中的字符串"Japan\0"是什么意思?如果程序员只写了"Japan",会有什么不同吗?
countryHeadSet 
    = countrySet.headSet("Japan");

你看过这个问题吗?https://dev59.com/7Wkw5IYBdhLWcg3woMBD - Sandip Subedi
'\0'字符是null字符。 - Mohsen_Fatemi
实际上,它是字符NUL,作为char,也称为空字符,但不是Java关键字null,不适用于原始类型。我提出这个问题是因为这些单词非常相似,但含义却截然不同。https://en.wikipedia.org/wiki/Null_character https://unicode-table.com/en/ https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-EscapeSequence - Lew Bloch
嗨,谢谢你的所有帮助。我已经找到了答案并在下面提供了。谢谢! - leeyuiwah
1个回答

4
我已经找到答案。感谢所有的想法。
其中一个使用字符串 + "\0" 成语的用途,特别是当您看到它与 SortedSet 的范围视图操作一起使用时,是用它来查找字符串的后继者
这样的后继者是必需的,因为这些范围视图操作(subSet()headSet()tailSet())提供了半开区间,并且您可能需要一个字符串的后继者来构造一个闭合区间。这在Sorted Set的Java文档中有解释。

几种方法返回具有受限范围的子集。这些范围是半开放的,即它们包括它们的低端点但不包括它们的高端点(如果适用)。如果您需要一个封闭范围(包括两个端点),并且元素类型允许计算给定值的后继者,则仅请求从lowEndpoint到successor(highEndpoint)的子范围即可。例如,假设s是一个排序的字符串集合。以下成语获得一个视图,其中包含s中的所有字符串,从低到高,包括:

SortedSet sub = s.subSet(low, high+"\0");

换句话说,以下两个调用之间的区别:
countrySet.headSet("Japan\0");
countrySet.headSet("Japan")

第一个会获取所有countrySet中从集合开头到包括字符串"Japan"的字符串(即范围为闭区间);而第二个将获取从集合开头到但不包括字符串"Japan"的所有字符串(即范围为半开区间)。

我包含了一个测试程序来演示这个习语的使用:

import java.util.Arrays;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

public class StringPlusNull {

    public static void main(String[] args) {
        List<String> countryList 
            = Arrays.asList("U.S.", "U.K.", "China", "Japan", "Korea");
        SortedSet<String> countrySet
            = new TreeSet<>(countryList);

        String toElement = "Japan";
        SortedSet<String> countryHeadSet 
            = countrySet.headSet(toElement);
        System.out.format("There are %d countries in the "
                + "(half-open) headset [, %s): %s%n"
                , countryHeadSet.size(), toElement, countryHeadSet);

        toElement = "Japan\0";
        countryHeadSet 
            = countrySet.headSet(toElement);
        System.out.format("There are %d countries in the "
                + "(half-open) headset [, %s): %s%n"
                , countryHeadSet.size(), toElement, countryHeadSet);
    }

}

输出结果将会是:
There are 1 countries in the (half-open) headset [, Japan): [China]
There are 2 countries in the (half-open) headset [, Japan ): [China, Japan]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接