Dyu Asked:2024-03-03 17:10:51 +0000 UTC2024-03-03 17:10:51 +0000 UTC 2024-03-03 17:10:51 +0000 UTC Java 中的 codePointAt() 方法 772 使用方法有区别吗 static int codePointAt(CharSequence seq, int index) 从课堂Character 上和 int codePointAt(int index) 来自班级String(第一个班级中使用的除外CharSequence)?结果似乎是一样的。 java 1 个回答 Voted Best Answer Nowhere Man 2024-03-03T20:21:03Z2024-03-03T20:21:03Z 这些方法在访问符号时的实现上略有不同。 示例(对于 Open JDK 8): Character.codePointAt(CharSequence seq, int index):对给定的输入参数 调用方法CharSequence::charAtseq public static int codePointAt(CharSequence seq, int index) { char c1 = seq.charAt(index); if (isHighSurrogate(c1) && ++index < seq.length()) { char c2 = seq.charAt(index); if (isLowSurrogate(c2)) { return toCodePoint(c1, c2); } } return c1; } 因此,对于字符串,该方法的实现String::charAt归结为检查索引并通过内部字符数组直接访问char[] value: // String::charAt public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index]; } String::codePointAt: 它实际上只是检查索引以StringIndexOutOfBoundsException在行溢出时引发特殊异常,并调用静态方法Character.codePointAtImpl(默认情况下仅在包中可用java.lang)向其传递对给定行的内部字符数组的引用: public int codePointAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return Character.codePointAtImpl(value, index, value.length); } 同样,该方法的实现Character.codePointAtImpl直接通过索引访问数组元素: static int codePointAtImpl(char[] a, int index, int limit) { char c1 = a[index]; if (isHighSurrogate(c1) && ++index < limit) { char c2 = a[index]; if (isLowSurrogate(c2)) { return toCodePoint(c1, c2); } } return c1; } 也就是说,调用该方法String::codePointAt在某种程度上更有效,因为它避免了对越界字符数组的双重检查,这种情况在调用该方法两次时会发生String::charAt。
这些方法在访问符号时的实现上略有不同。
示例(对于 Open JDK 8):
Character.codePointAt(CharSequence seq, int index):对给定的输入参数调用方法
CharSequence::charAtseq因此,对于字符串,该方法的实现
String::charAt归结为检查索引并通过内部字符数组直接访问char[] value:String::codePointAt:它实际上只是检查索引以
StringIndexOutOfBoundsException在行溢出时引发特殊异常,并调用静态方法Character.codePointAtImpl(默认情况下仅在包中可用java.lang)向其传递对给定行的内部字符数组的引用:同样,该方法的实现
Character.codePointAtImpl直接通过索引访问数组元素:也就是说,调用该方法
String::codePointAt在某种程度上更有效,因为它避免了对越界字符数组的双重检查,这种情况在调用该方法两次时会发生String::charAt。