1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/emul/pom.xml Fri Sep 28 17:59:03 2012 +0200
1.3 @@ -0,0 +1,40 @@
1.4 +<?xml version="1.0"?>
1.5 +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
1.6 + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
1.7 + <modelVersion>4.0.0</modelVersion>
1.8 + <parent>
1.9 + <groupId>org.apidesign</groupId>
1.10 + <artifactId>bck2brwsr</artifactId>
1.11 + <version>1.0-SNAPSHOT</version>
1.12 + </parent>
1.13 + <groupId>org.apidesign.bck2brwsr</groupId>
1.14 + <artifactId>emul</artifactId>
1.15 + <version>1.0-SNAPSHOT</version>
1.16 + <name>Java API Emulation</name>
1.17 + <url>http://maven.apache.org</url>
1.18 + <properties>
1.19 + <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
1.20 + </properties>
1.21 + <dependencies>
1.22 + <dependency>
1.23 + <groupId>junit</groupId>
1.24 + <artifactId>junit</artifactId>
1.25 + <version>3.8.1</version>
1.26 + <scope>test</scope>
1.27 + </dependency>
1.28 + </dependencies>
1.29 + <build>
1.30 + <plugins>
1.31 + <plugin>
1.32 + <groupId>org.apache.maven.plugins</groupId>
1.33 + <artifactId>maven-compiler-plugin</artifactId>
1.34 + <version>2.5.1</version>
1.35 + <configuration>
1.36 + <compilerArguments>
1.37 + <bootclasspath>non-existing</bootclasspath>
1.38 + </compilerArguments>
1.39 + </configuration>
1.40 + </plugin>
1.41 + </plugins>
1.42 + </build>
1.43 +</project>
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/emul/src/main/java/java/lang/CloneNotSupportedException.java Fri Sep 28 17:59:03 2012 +0200
2.3 @@ -0,0 +1,65 @@
2.4 +/*
2.5 + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
2.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
2.7 + *
2.8 + * This code is free software; you can redistribute it and/or modify it
2.9 + * under the terms of the GNU General Public License version 2 only, as
2.10 + * published by the Free Software Foundation. Oracle designates this
2.11 + * particular file as subject to the "Classpath" exception as provided
2.12 + * by Oracle in the LICENSE file that accompanied this code.
2.13 + *
2.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
2.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
2.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
2.17 + * version 2 for more details (a copy is included in the LICENSE file that
2.18 + * accompanied this code).
2.19 + *
2.20 + * You should have received a copy of the GNU General Public License version
2.21 + * 2 along with this work; if not, write to the Free Software Foundation,
2.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
2.23 + *
2.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2.25 + * or visit www.oracle.com if you need additional information or have any
2.26 + * questions.
2.27 + */
2.28 +
2.29 +package java.lang;
2.30 +
2.31 +/**
2.32 + * Thrown to indicate that the <code>clone</code> method in class
2.33 + * <code>Object</code> has been called to clone an object, but that
2.34 + * the object's class does not implement the <code>Cloneable</code>
2.35 + * interface.
2.36 + * <p>
2.37 + * Applications that override the <code>clone</code> method can also
2.38 + * throw this exception to indicate that an object could not or
2.39 + * should not be cloned.
2.40 + *
2.41 + * @author unascribed
2.42 + * @see java.lang.Cloneable
2.43 + * @see java.lang.Object#clone()
2.44 + * @since JDK1.0
2.45 + */
2.46 +
2.47 +public
2.48 +class CloneNotSupportedException extends Exception {
2.49 + private static final long serialVersionUID = 5195511250079656443L;
2.50 +
2.51 + /**
2.52 + * Constructs a <code>CloneNotSupportedException</code> with no
2.53 + * detail message.
2.54 + */
2.55 + public CloneNotSupportedException() {
2.56 + super();
2.57 + }
2.58 +
2.59 + /**
2.60 + * Constructs a <code>CloneNotSupportedException</code> with the
2.61 + * specified detail message.
2.62 + *
2.63 + * @param s the detail message.
2.64 + */
2.65 + public CloneNotSupportedException(String s) {
2.66 + super(s);
2.67 + }
2.68 +}
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/emul/src/main/java/java/lang/IllegalArgumentException.java Fri Sep 28 17:59:03 2012 +0200
3.3 @@ -0,0 +1,95 @@
3.4 +/*
3.5 + * Copyright (c) 1994, 2003, Oracle and/or its affiliates. All rights reserved.
3.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3.7 + *
3.8 + * This code is free software; you can redistribute it and/or modify it
3.9 + * under the terms of the GNU General Public License version 2 only, as
3.10 + * published by the Free Software Foundation. Oracle designates this
3.11 + * particular file as subject to the "Classpath" exception as provided
3.12 + * by Oracle in the LICENSE file that accompanied this code.
3.13 + *
3.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
3.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
3.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
3.17 + * version 2 for more details (a copy is included in the LICENSE file that
3.18 + * accompanied this code).
3.19 + *
3.20 + * You should have received a copy of the GNU General Public License version
3.21 + * 2 along with this work; if not, write to the Free Software Foundation,
3.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
3.23 + *
3.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
3.25 + * or visit www.oracle.com if you need additional information or have any
3.26 + * questions.
3.27 + */
3.28 +
3.29 +package java.lang;
3.30 +
3.31 +/**
3.32 + * Thrown to indicate that a method has been passed an illegal or
3.33 + * inappropriate argument.
3.34 + *
3.35 + * @author unascribed
3.36 + * @see java.lang.Thread#setPriority(int)
3.37 + * @since JDK1.0
3.38 + */
3.39 +public
3.40 +class IllegalArgumentException extends RuntimeException {
3.41 + /**
3.42 + * Constructs an <code>IllegalArgumentException</code> with no
3.43 + * detail message.
3.44 + */
3.45 + public IllegalArgumentException() {
3.46 + super();
3.47 + }
3.48 +
3.49 + /**
3.50 + * Constructs an <code>IllegalArgumentException</code> with the
3.51 + * specified detail message.
3.52 + *
3.53 + * @param s the detail message.
3.54 + */
3.55 + public IllegalArgumentException(String s) {
3.56 + super(s);
3.57 + }
3.58 +
3.59 + /**
3.60 + * Constructs a new exception with the specified detail message and
3.61 + * cause.
3.62 + *
3.63 + * <p>Note that the detail message associated with <code>cause</code> is
3.64 + * <i>not</i> automatically incorporated in this exception's detail
3.65 + * message.
3.66 + *
3.67 + * @param message the detail message (which is saved for later retrieval
3.68 + * by the {@link Throwable#getMessage()} method).
3.69 + * @param cause the cause (which is saved for later retrieval by the
3.70 + * {@link Throwable#getCause()} method). (A <tt>null</tt> value
3.71 + * is permitted, and indicates that the cause is nonexistent or
3.72 + * unknown.)
3.73 + * @since 1.5
3.74 + */
3.75 + public IllegalArgumentException(String message, Throwable cause) {
3.76 + super(message, cause);
3.77 + }
3.78 +
3.79 + /**
3.80 + * Constructs a new exception with the specified cause and a detail
3.81 + * message of <tt>(cause==null ? null : cause.toString())</tt> (which
3.82 + * typically contains the class and detail message of <tt>cause</tt>).
3.83 + * This constructor is useful for exceptions that are little more than
3.84 + * wrappers for other throwables (for example, {@link
3.85 + * java.security.PrivilegedActionException}).
3.86 + *
3.87 + * @param cause the cause (which is saved for later retrieval by the
3.88 + * {@link Throwable#getCause()} method). (A <tt>null</tt> value is
3.89 + * permitted, and indicates that the cause is nonexistent or
3.90 + * unknown.)
3.91 + * @since 1.5
3.92 + */
3.93 + public IllegalArgumentException(Throwable cause) {
3.94 + super(cause);
3.95 + }
3.96 +
3.97 + private static final long serialVersionUID = -5365630128856068164L;
3.98 +}
4.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
4.2 +++ b/emul/src/main/java/java/lang/Integer.java Fri Sep 28 17:59:03 2012 +0200
4.3 @@ -0,0 +1,1244 @@
4.4 +/*
4.5 + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
4.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4.7 + *
4.8 + * This code is free software; you can redistribute it and/or modify it
4.9 + * under the terms of the GNU General Public License version 2 only, as
4.10 + * published by the Free Software Foundation. Oracle designates this
4.11 + * particular file as subject to the "Classpath" exception as provided
4.12 + * by Oracle in the LICENSE file that accompanied this code.
4.13 + *
4.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
4.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
4.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
4.17 + * version 2 for more details (a copy is included in the LICENSE file that
4.18 + * accompanied this code).
4.19 + *
4.20 + * You should have received a copy of the GNU General Public License version
4.21 + * 2 along with this work; if not, write to the Free Software Foundation,
4.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
4.23 + *
4.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
4.25 + * or visit www.oracle.com if you need additional information or have any
4.26 + * questions.
4.27 + */
4.28 +
4.29 +package java.lang;
4.30 +
4.31 +import java.util.Properties;
4.32 +
4.33 +/**
4.34 + * The {@code Integer} class wraps a value of the primitive type
4.35 + * {@code int} in an object. An object of type {@code Integer}
4.36 + * contains a single field whose type is {@code int}.
4.37 + *
4.38 + * <p>In addition, this class provides several methods for converting
4.39 + * an {@code int} to a {@code String} and a {@code String} to an
4.40 + * {@code int}, as well as other constants and methods useful when
4.41 + * dealing with an {@code int}.
4.42 + *
4.43 + * <p>Implementation note: The implementations of the "bit twiddling"
4.44 + * methods (such as {@link #highestOneBit(int) highestOneBit} and
4.45 + * {@link #numberOfTrailingZeros(int) numberOfTrailingZeros}) are
4.46 + * based on material from Henry S. Warren, Jr.'s <i>Hacker's
4.47 + * Delight</i>, (Addison Wesley, 2002).
4.48 + *
4.49 + * @author Lee Boynton
4.50 + * @author Arthur van Hoff
4.51 + * @author Josh Bloch
4.52 + * @author Joseph D. Darcy
4.53 + * @since JDK1.0
4.54 + */
4.55 +public final class Integer extends Number implements Comparable<Integer> {
4.56 + /**
4.57 + * A constant holding the minimum value an {@code int} can
4.58 + * have, -2<sup>31</sup>.
4.59 + */
4.60 + public static final int MIN_VALUE = 0x80000000;
4.61 +
4.62 + /**
4.63 + * A constant holding the maximum value an {@code int} can
4.64 + * have, 2<sup>31</sup>-1.
4.65 + */
4.66 + public static final int MAX_VALUE = 0x7fffffff;
4.67 +
4.68 + /**
4.69 + * The {@code Class} instance representing the primitive type
4.70 + * {@code int}.
4.71 + *
4.72 + * @since JDK1.1
4.73 + */
4.74 + public static final Class<Integer> TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
4.75 +
4.76 + /**
4.77 + * All possible chars for representing a number as a String
4.78 + */
4.79 + final static char[] digits = {
4.80 + '0' , '1' , '2' , '3' , '4' , '5' ,
4.81 + '6' , '7' , '8' , '9' , 'a' , 'b' ,
4.82 + 'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
4.83 + 'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
4.84 + 'o' , 'p' , 'q' , 'r' , 's' , 't' ,
4.85 + 'u' , 'v' , 'w' , 'x' , 'y' , 'z'
4.86 + };
4.87 +
4.88 + /**
4.89 + * Returns a string representation of the first argument in the
4.90 + * radix specified by the second argument.
4.91 + *
4.92 + * <p>If the radix is smaller than {@code Character.MIN_RADIX}
4.93 + * or larger than {@code Character.MAX_RADIX}, then the radix
4.94 + * {@code 10} is used instead.
4.95 + *
4.96 + * <p>If the first argument is negative, the first element of the
4.97 + * result is the ASCII minus character {@code '-'}
4.98 + * (<code>'\u002D'</code>). If the first argument is not
4.99 + * negative, no sign character appears in the result.
4.100 + *
4.101 + * <p>The remaining characters of the result represent the magnitude
4.102 + * of the first argument. If the magnitude is zero, it is
4.103 + * represented by a single zero character {@code '0'}
4.104 + * (<code>'\u0030'</code>); otherwise, the first character of
4.105 + * the representation of the magnitude will not be the zero
4.106 + * character. The following ASCII characters are used as digits:
4.107 + *
4.108 + * <blockquote>
4.109 + * {@code 0123456789abcdefghijklmnopqrstuvwxyz}
4.110 + * </blockquote>
4.111 + *
4.112 + * These are <code>'\u0030'</code> through
4.113 + * <code>'\u0039'</code> and <code>'\u0061'</code> through
4.114 + * <code>'\u007A'</code>. If {@code radix} is
4.115 + * <var>N</var>, then the first <var>N</var> of these characters
4.116 + * are used as radix-<var>N</var> digits in the order shown. Thus,
4.117 + * the digits for hexadecimal (radix 16) are
4.118 + * {@code 0123456789abcdef}. If uppercase letters are
4.119 + * desired, the {@link java.lang.String#toUpperCase()} method may
4.120 + * be called on the result:
4.121 + *
4.122 + * <blockquote>
4.123 + * {@code Integer.toString(n, 16).toUpperCase()}
4.124 + * </blockquote>
4.125 + *
4.126 + * @param i an integer to be converted to a string.
4.127 + * @param radix the radix to use in the string representation.
4.128 + * @return a string representation of the argument in the specified radix.
4.129 + * @see java.lang.Character#MAX_RADIX
4.130 + * @see java.lang.Character#MIN_RADIX
4.131 + */
4.132 + public static String toString(int i, int radix) {
4.133 +
4.134 + if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
4.135 + radix = 10;
4.136 +
4.137 + /* Use the faster version */
4.138 + if (radix == 10) {
4.139 + return toString(i);
4.140 + }
4.141 +
4.142 + char buf[] = new char[33];
4.143 + boolean negative = (i < 0);
4.144 + int charPos = 32;
4.145 +
4.146 + if (!negative) {
4.147 + i = -i;
4.148 + }
4.149 +
4.150 + while (i <= -radix) {
4.151 + buf[charPos--] = digits[-(i % radix)];
4.152 + i = i / radix;
4.153 + }
4.154 + buf[charPos] = digits[-i];
4.155 +
4.156 + if (negative) {
4.157 + buf[--charPos] = '-';
4.158 + }
4.159 +
4.160 + return new String(buf, charPos, (33 - charPos));
4.161 + }
4.162 +
4.163 + /**
4.164 + * Returns a string representation of the integer argument as an
4.165 + * unsigned integer in base 16.
4.166 + *
4.167 + * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
4.168 + * if the argument is negative; otherwise, it is equal to the
4.169 + * argument. This value is converted to a string of ASCII digits
4.170 + * in hexadecimal (base 16) with no extra leading
4.171 + * {@code 0}s. If the unsigned magnitude is zero, it is
4.172 + * represented by a single zero character {@code '0'}
4.173 + * (<code>'\u0030'</code>); otherwise, the first character of
4.174 + * the representation of the unsigned magnitude will not be the
4.175 + * zero character. The following characters are used as
4.176 + * hexadecimal digits:
4.177 + *
4.178 + * <blockquote>
4.179 + * {@code 0123456789abcdef}
4.180 + * </blockquote>
4.181 + *
4.182 + * These are the characters <code>'\u0030'</code> through
4.183 + * <code>'\u0039'</code> and <code>'\u0061'</code> through
4.184 + * <code>'\u0066'</code>. If uppercase letters are
4.185 + * desired, the {@link java.lang.String#toUpperCase()} method may
4.186 + * be called on the result:
4.187 + *
4.188 + * <blockquote>
4.189 + * {@code Integer.toHexString(n).toUpperCase()}
4.190 + * </blockquote>
4.191 + *
4.192 + * @param i an integer to be converted to a string.
4.193 + * @return the string representation of the unsigned integer value
4.194 + * represented by the argument in hexadecimal (base 16).
4.195 + * @since JDK1.0.2
4.196 + */
4.197 + public static String toHexString(int i) {
4.198 + return toUnsignedString(i, 4);
4.199 + }
4.200 +
4.201 + /**
4.202 + * Returns a string representation of the integer argument as an
4.203 + * unsigned integer in base 8.
4.204 + *
4.205 + * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
4.206 + * if the argument is negative; otherwise, it is equal to the
4.207 + * argument. This value is converted to a string of ASCII digits
4.208 + * in octal (base 8) with no extra leading {@code 0}s.
4.209 + *
4.210 + * <p>If the unsigned magnitude is zero, it is represented by a
4.211 + * single zero character {@code '0'}
4.212 + * (<code>'\u0030'</code>); otherwise, the first character of
4.213 + * the representation of the unsigned magnitude will not be the
4.214 + * zero character. The following characters are used as octal
4.215 + * digits:
4.216 + *
4.217 + * <blockquote>
4.218 + * {@code 01234567}
4.219 + * </blockquote>
4.220 + *
4.221 + * These are the characters <code>'\u0030'</code> through
4.222 + * <code>'\u0037'</code>.
4.223 + *
4.224 + * @param i an integer to be converted to a string.
4.225 + * @return the string representation of the unsigned integer value
4.226 + * represented by the argument in octal (base 8).
4.227 + * @since JDK1.0.2
4.228 + */
4.229 + public static String toOctalString(int i) {
4.230 + return toUnsignedString(i, 3);
4.231 + }
4.232 +
4.233 + /**
4.234 + * Returns a string representation of the integer argument as an
4.235 + * unsigned integer in base 2.
4.236 + *
4.237 + * <p>The unsigned integer value is the argument plus 2<sup>32</sup>
4.238 + * if the argument is negative; otherwise it is equal to the
4.239 + * argument. This value is converted to a string of ASCII digits
4.240 + * in binary (base 2) with no extra leading {@code 0}s.
4.241 + * If the unsigned magnitude is zero, it is represented by a
4.242 + * single zero character {@code '0'}
4.243 + * (<code>'\u0030'</code>); otherwise, the first character of
4.244 + * the representation of the unsigned magnitude will not be the
4.245 + * zero character. The characters {@code '0'}
4.246 + * (<code>'\u0030'</code>) and {@code '1'}
4.247 + * (<code>'\u0031'</code>) are used as binary digits.
4.248 + *
4.249 + * @param i an integer to be converted to a string.
4.250 + * @return the string representation of the unsigned integer value
4.251 + * represented by the argument in binary (base 2).
4.252 + * @since JDK1.0.2
4.253 + */
4.254 + public static String toBinaryString(int i) {
4.255 + return toUnsignedString(i, 1);
4.256 + }
4.257 +
4.258 + /**
4.259 + * Convert the integer to an unsigned number.
4.260 + */
4.261 + private static String toUnsignedString(int i, int shift) {
4.262 + char[] buf = new char[32];
4.263 + int charPos = 32;
4.264 + int radix = 1 << shift;
4.265 + int mask = radix - 1;
4.266 + do {
4.267 + buf[--charPos] = digits[i & mask];
4.268 + i >>>= shift;
4.269 + } while (i != 0);
4.270 +
4.271 + return new String(buf, charPos, (32 - charPos));
4.272 + }
4.273 +
4.274 +
4.275 + final static char [] DigitTens = {
4.276 + '0', '0', '0', '0', '0', '0', '0', '0', '0', '0',
4.277 + '1', '1', '1', '1', '1', '1', '1', '1', '1', '1',
4.278 + '2', '2', '2', '2', '2', '2', '2', '2', '2', '2',
4.279 + '3', '3', '3', '3', '3', '3', '3', '3', '3', '3',
4.280 + '4', '4', '4', '4', '4', '4', '4', '4', '4', '4',
4.281 + '5', '5', '5', '5', '5', '5', '5', '5', '5', '5',
4.282 + '6', '6', '6', '6', '6', '6', '6', '6', '6', '6',
4.283 + '7', '7', '7', '7', '7', '7', '7', '7', '7', '7',
4.284 + '8', '8', '8', '8', '8', '8', '8', '8', '8', '8',
4.285 + '9', '9', '9', '9', '9', '9', '9', '9', '9', '9',
4.286 + } ;
4.287 +
4.288 + final static char [] DigitOnes = {
4.289 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.290 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.291 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.292 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.293 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.294 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.295 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.296 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.297 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.298 + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
4.299 + } ;
4.300 +
4.301 + // I use the "invariant division by multiplication" trick to
4.302 + // accelerate Integer.toString. In particular we want to
4.303 + // avoid division by 10.
4.304 + //
4.305 + // The "trick" has roughly the same performance characteristics
4.306 + // as the "classic" Integer.toString code on a non-JIT VM.
4.307 + // The trick avoids .rem and .div calls but has a longer code
4.308 + // path and is thus dominated by dispatch overhead. In the
4.309 + // JIT case the dispatch overhead doesn't exist and the
4.310 + // "trick" is considerably faster than the classic code.
4.311 + //
4.312 + // TODO-FIXME: convert (x * 52429) into the equiv shift-add
4.313 + // sequence.
4.314 + //
4.315 + // RE: Division by Invariant Integers using Multiplication
4.316 + // T Gralund, P Montgomery
4.317 + // ACM PLDI 1994
4.318 + //
4.319 +
4.320 + /**
4.321 + * Returns a {@code String} object representing the
4.322 + * specified integer. The argument is converted to signed decimal
4.323 + * representation and returned as a string, exactly as if the
4.324 + * argument and radix 10 were given as arguments to the {@link
4.325 + * #toString(int, int)} method.
4.326 + *
4.327 + * @param i an integer to be converted.
4.328 + * @return a string representation of the argument in base 10.
4.329 + */
4.330 + public static String toString(int i) {
4.331 + if (i == Integer.MIN_VALUE)
4.332 + return "-2147483648";
4.333 + int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
4.334 + char[] buf = new char[size];
4.335 + getChars(i, size, buf);
4.336 + return new String(0, size, buf);
4.337 + }
4.338 +
4.339 + /**
4.340 + * Places characters representing the integer i into the
4.341 + * character array buf. The characters are placed into
4.342 + * the buffer backwards starting with the least significant
4.343 + * digit at the specified index (exclusive), and working
4.344 + * backwards from there.
4.345 + *
4.346 + * Will fail if i == Integer.MIN_VALUE
4.347 + */
4.348 + static void getChars(int i, int index, char[] buf) {
4.349 + int q, r;
4.350 + int charPos = index;
4.351 + char sign = 0;
4.352 +
4.353 + if (i < 0) {
4.354 + sign = '-';
4.355 + i = -i;
4.356 + }
4.357 +
4.358 + // Generate two digits per iteration
4.359 + while (i >= 65536) {
4.360 + q = i / 100;
4.361 + // really: r = i - (q * 100);
4.362 + r = i - ((q << 6) + (q << 5) + (q << 2));
4.363 + i = q;
4.364 + buf [--charPos] = DigitOnes[r];
4.365 + buf [--charPos] = DigitTens[r];
4.366 + }
4.367 +
4.368 + // Fall thru to fast mode for smaller numbers
4.369 + // assert(i <= 65536, i);
4.370 + for (;;) {
4.371 + q = (i * 52429) >>> (16+3);
4.372 + r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ...
4.373 + buf [--charPos] = digits [r];
4.374 + i = q;
4.375 + if (i == 0) break;
4.376 + }
4.377 + if (sign != 0) {
4.378 + buf [--charPos] = sign;
4.379 + }
4.380 + }
4.381 +
4.382 + final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
4.383 + 99999999, 999999999, Integer.MAX_VALUE };
4.384 +
4.385 + // Requires positive x
4.386 + static int stringSize(int x) {
4.387 + for (int i=0; ; i++)
4.388 + if (x <= sizeTable[i])
4.389 + return i+1;
4.390 + }
4.391 +
4.392 + /**
4.393 + * Parses the string argument as a signed integer in the radix
4.394 + * specified by the second argument. The characters in the string
4.395 + * must all be digits of the specified radix (as determined by
4.396 + * whether {@link java.lang.Character#digit(char, int)} returns a
4.397 + * nonnegative value), except that the first character may be an
4.398 + * ASCII minus sign {@code '-'} (<code>'\u002D'</code>) to
4.399 + * indicate a negative value or an ASCII plus sign {@code '+'}
4.400 + * (<code>'\u002B'</code>) to indicate a positive value. The
4.401 + * resulting integer value is returned.
4.402 + *
4.403 + * <p>An exception of type {@code NumberFormatException} is
4.404 + * thrown if any of the following situations occurs:
4.405 + * <ul>
4.406 + * <li>The first argument is {@code null} or is a string of
4.407 + * length zero.
4.408 + *
4.409 + * <li>The radix is either smaller than
4.410 + * {@link java.lang.Character#MIN_RADIX} or
4.411 + * larger than {@link java.lang.Character#MAX_RADIX}.
4.412 + *
4.413 + * <li>Any character of the string is not a digit of the specified
4.414 + * radix, except that the first character may be a minus sign
4.415 + * {@code '-'} (<code>'\u002D'</code>) or plus sign
4.416 + * {@code '+'} (<code>'\u002B'</code>) provided that the
4.417 + * string is longer than length 1.
4.418 + *
4.419 + * <li>The value represented by the string is not a value of type
4.420 + * {@code int}.
4.421 + * </ul>
4.422 + *
4.423 + * <p>Examples:
4.424 + * <blockquote><pre>
4.425 + * parseInt("0", 10) returns 0
4.426 + * parseInt("473", 10) returns 473
4.427 + * parseInt("+42", 10) returns 42
4.428 + * parseInt("-0", 10) returns 0
4.429 + * parseInt("-FF", 16) returns -255
4.430 + * parseInt("1100110", 2) returns 102
4.431 + * parseInt("2147483647", 10) returns 2147483647
4.432 + * parseInt("-2147483648", 10) returns -2147483648
4.433 + * parseInt("2147483648", 10) throws a NumberFormatException
4.434 + * parseInt("99", 8) throws a NumberFormatException
4.435 + * parseInt("Kona", 10) throws a NumberFormatException
4.436 + * parseInt("Kona", 27) returns 411787
4.437 + * </pre></blockquote>
4.438 + *
4.439 + * @param s the {@code String} containing the integer
4.440 + * representation to be parsed
4.441 + * @param radix the radix to be used while parsing {@code s}.
4.442 + * @return the integer represented by the string argument in the
4.443 + * specified radix.
4.444 + * @exception NumberFormatException if the {@code String}
4.445 + * does not contain a parsable {@code int}.
4.446 + */
4.447 + public static int parseInt(String s, int radix)
4.448 + throws NumberFormatException
4.449 + {
4.450 + /*
4.451 + * WARNING: This method may be invoked early during VM initialization
4.452 + * before IntegerCache is initialized. Care must be taken to not use
4.453 + * the valueOf method.
4.454 + */
4.455 +
4.456 + if (s == null) {
4.457 + throw new NumberFormatException("null");
4.458 + }
4.459 +
4.460 + if (radix < Character.MIN_RADIX) {
4.461 + throw new NumberFormatException("radix " + radix +
4.462 + " less than Character.MIN_RADIX");
4.463 + }
4.464 +
4.465 + if (radix > Character.MAX_RADIX) {
4.466 + throw new NumberFormatException("radix " + radix +
4.467 + " greater than Character.MAX_RADIX");
4.468 + }
4.469 +
4.470 + int result = 0;
4.471 + boolean negative = false;
4.472 + int i = 0, len = s.length();
4.473 + int limit = -Integer.MAX_VALUE;
4.474 + int multmin;
4.475 + int digit;
4.476 +
4.477 + if (len > 0) {
4.478 + char firstChar = s.charAt(0);
4.479 + if (firstChar < '0') { // Possible leading "+" or "-"
4.480 + if (firstChar == '-') {
4.481 + negative = true;
4.482 + limit = Integer.MIN_VALUE;
4.483 + } else if (firstChar != '+')
4.484 + throw NumberFormatException.forInputString(s);
4.485 +
4.486 + if (len == 1) // Cannot have lone "+" or "-"
4.487 + throw NumberFormatException.forInputString(s);
4.488 + i++;
4.489 + }
4.490 + multmin = limit / radix;
4.491 + while (i < len) {
4.492 + // Accumulating negatively avoids surprises near MAX_VALUE
4.493 + digit = Character.digit(s.charAt(i++),radix);
4.494 + if (digit < 0) {
4.495 + throw NumberFormatException.forInputString(s);
4.496 + }
4.497 + if (result < multmin) {
4.498 + throw NumberFormatException.forInputString(s);
4.499 + }
4.500 + result *= radix;
4.501 + if (result < limit + digit) {
4.502 + throw NumberFormatException.forInputString(s);
4.503 + }
4.504 + result -= digit;
4.505 + }
4.506 + } else {
4.507 + throw NumberFormatException.forInputString(s);
4.508 + }
4.509 + return negative ? result : -result;
4.510 + }
4.511 +
4.512 + /**
4.513 + * Parses the string argument as a signed decimal integer. The
4.514 + * characters in the string must all be decimal digits, except
4.515 + * that the first character may be an ASCII minus sign {@code '-'}
4.516 + * (<code>'\u002D'</code>) to indicate a negative value or an
4.517 + * ASCII plus sign {@code '+'} (<code>'\u002B'</code>) to
4.518 + * indicate a positive value. The resulting integer value is
4.519 + * returned, exactly as if the argument and the radix 10 were
4.520 + * given as arguments to the {@link #parseInt(java.lang.String,
4.521 + * int)} method.
4.522 + *
4.523 + * @param s a {@code String} containing the {@code int}
4.524 + * representation to be parsed
4.525 + * @return the integer value represented by the argument in decimal.
4.526 + * @exception NumberFormatException if the string does not contain a
4.527 + * parsable integer.
4.528 + */
4.529 + public static int parseInt(String s) throws NumberFormatException {
4.530 + return parseInt(s,10);
4.531 + }
4.532 +
4.533 + /**
4.534 + * Returns an {@code Integer} object holding the value
4.535 + * extracted from the specified {@code String} when parsed
4.536 + * with the radix given by the second argument. The first argument
4.537 + * is interpreted as representing a signed integer in the radix
4.538 + * specified by the second argument, exactly as if the arguments
4.539 + * were given to the {@link #parseInt(java.lang.String, int)}
4.540 + * method. The result is an {@code Integer} object that
4.541 + * represents the integer value specified by the string.
4.542 + *
4.543 + * <p>In other words, this method returns an {@code Integer}
4.544 + * object equal to the value of:
4.545 + *
4.546 + * <blockquote>
4.547 + * {@code new Integer(Integer.parseInt(s, radix))}
4.548 + * </blockquote>
4.549 + *
4.550 + * @param s the string to be parsed.
4.551 + * @param radix the radix to be used in interpreting {@code s}
4.552 + * @return an {@code Integer} object holding the value
4.553 + * represented by the string argument in the specified
4.554 + * radix.
4.555 + * @exception NumberFormatException if the {@code String}
4.556 + * does not contain a parsable {@code int}.
4.557 + */
4.558 + public static Integer valueOf(String s, int radix) throws NumberFormatException {
4.559 + return Integer.valueOf(parseInt(s,radix));
4.560 + }
4.561 +
4.562 + /**
4.563 + * Returns an {@code Integer} object holding the
4.564 + * value of the specified {@code String}. The argument is
4.565 + * interpreted as representing a signed decimal integer, exactly
4.566 + * as if the argument were given to the {@link
4.567 + * #parseInt(java.lang.String)} method. The result is an
4.568 + * {@code Integer} object that represents the integer value
4.569 + * specified by the string.
4.570 + *
4.571 + * <p>In other words, this method returns an {@code Integer}
4.572 + * object equal to the value of:
4.573 + *
4.574 + * <blockquote>
4.575 + * {@code new Integer(Integer.parseInt(s))}
4.576 + * </blockquote>
4.577 + *
4.578 + * @param s the string to be parsed.
4.579 + * @return an {@code Integer} object holding the value
4.580 + * represented by the string argument.
4.581 + * @exception NumberFormatException if the string cannot be parsed
4.582 + * as an integer.
4.583 + */
4.584 + public static Integer valueOf(String s) throws NumberFormatException {
4.585 + return Integer.valueOf(parseInt(s, 10));
4.586 + }
4.587 +
4.588 + /**
4.589 + * Cache to support the object identity semantics of autoboxing for values between
4.590 + * -128 and 127 (inclusive) as required by JLS.
4.591 + *
4.592 + * The cache is initialized on first usage. The size of the cache
4.593 + * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
4.594 + * During VM initialization, java.lang.Integer.IntegerCache.high property
4.595 + * may be set and saved in the private system properties in the
4.596 + * sun.misc.VM class.
4.597 + */
4.598 +
4.599 + private static class IntegerCache {
4.600 + static final int low = -128;
4.601 + static final int high;
4.602 + static final Integer cache[];
4.603 +
4.604 + static {
4.605 + // high value may be configured by property
4.606 + int h = 127;
4.607 + String integerCacheHighPropValue =
4.608 + sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
4.609 + if (integerCacheHighPropValue != null) {
4.610 + int i = parseInt(integerCacheHighPropValue);
4.611 + i = Math.max(i, 127);
4.612 + // Maximum array size is Integer.MAX_VALUE
4.613 + h = Math.min(i, Integer.MAX_VALUE - (-low));
4.614 + }
4.615 + high = h;
4.616 +
4.617 + cache = new Integer[(high - low) + 1];
4.618 + int j = low;
4.619 + for(int k = 0; k < cache.length; k++)
4.620 + cache[k] = new Integer(j++);
4.621 + }
4.622 +
4.623 + private IntegerCache() {}
4.624 + }
4.625 +
4.626 + /**
4.627 + * Returns an {@code Integer} instance representing the specified
4.628 + * {@code int} value. If a new {@code Integer} instance is not
4.629 + * required, this method should generally be used in preference to
4.630 + * the constructor {@link #Integer(int)}, as this method is likely
4.631 + * to yield significantly better space and time performance by
4.632 + * caching frequently requested values.
4.633 + *
4.634 + * This method will always cache values in the range -128 to 127,
4.635 + * inclusive, and may cache other values outside of this range.
4.636 + *
4.637 + * @param i an {@code int} value.
4.638 + * @return an {@code Integer} instance representing {@code i}.
4.639 + * @since 1.5
4.640 + */
4.641 + public static Integer valueOf(int i) {
4.642 + assert IntegerCache.high >= 127;
4.643 + if (i >= IntegerCache.low && i <= IntegerCache.high)
4.644 + return IntegerCache.cache[i + (-IntegerCache.low)];
4.645 + return new Integer(i);
4.646 + }
4.647 +
4.648 + /**
4.649 + * The value of the {@code Integer}.
4.650 + *
4.651 + * @serial
4.652 + */
4.653 + private final int value;
4.654 +
4.655 + /**
4.656 + * Constructs a newly allocated {@code Integer} object that
4.657 + * represents the specified {@code int} value.
4.658 + *
4.659 + * @param value the value to be represented by the
4.660 + * {@code Integer} object.
4.661 + */
4.662 + public Integer(int value) {
4.663 + this.value = value;
4.664 + }
4.665 +
4.666 + /**
4.667 + * Constructs a newly allocated {@code Integer} object that
4.668 + * represents the {@code int} value indicated by the
4.669 + * {@code String} parameter. The string is converted to an
4.670 + * {@code int} value in exactly the manner used by the
4.671 + * {@code parseInt} method for radix 10.
4.672 + *
4.673 + * @param s the {@code String} to be converted to an
4.674 + * {@code Integer}.
4.675 + * @exception NumberFormatException if the {@code String} does not
4.676 + * contain a parsable integer.
4.677 + * @see java.lang.Integer#parseInt(java.lang.String, int)
4.678 + */
4.679 + public Integer(String s) throws NumberFormatException {
4.680 + this.value = parseInt(s, 10);
4.681 + }
4.682 +
4.683 + /**
4.684 + * Returns the value of this {@code Integer} as a
4.685 + * {@code byte}.
4.686 + */
4.687 + public byte byteValue() {
4.688 + return (byte)value;
4.689 + }
4.690 +
4.691 + /**
4.692 + * Returns the value of this {@code Integer} as a
4.693 + * {@code short}.
4.694 + */
4.695 + public short shortValue() {
4.696 + return (short)value;
4.697 + }
4.698 +
4.699 + /**
4.700 + * Returns the value of this {@code Integer} as an
4.701 + * {@code int}.
4.702 + */
4.703 + public int intValue() {
4.704 + return value;
4.705 + }
4.706 +
4.707 + /**
4.708 + * Returns the value of this {@code Integer} as a
4.709 + * {@code long}.
4.710 + */
4.711 + public long longValue() {
4.712 + return (long)value;
4.713 + }
4.714 +
4.715 + /**
4.716 + * Returns the value of this {@code Integer} as a
4.717 + * {@code float}.
4.718 + */
4.719 + public float floatValue() {
4.720 + return (float)value;
4.721 + }
4.722 +
4.723 + /**
4.724 + * Returns the value of this {@code Integer} as a
4.725 + * {@code double}.
4.726 + */
4.727 + public double doubleValue() {
4.728 + return (double)value;
4.729 + }
4.730 +
4.731 + /**
4.732 + * Returns a {@code String} object representing this
4.733 + * {@code Integer}'s value. The value is converted to signed
4.734 + * decimal representation and returned as a string, exactly as if
4.735 + * the integer value were given as an argument to the {@link
4.736 + * java.lang.Integer#toString(int)} method.
4.737 + *
4.738 + * @return a string representation of the value of this object in
4.739 + * base 10.
4.740 + */
4.741 + public String toString() {
4.742 + return toString(value);
4.743 + }
4.744 +
4.745 + /**
4.746 + * Returns a hash code for this {@code Integer}.
4.747 + *
4.748 + * @return a hash code value for this object, equal to the
4.749 + * primitive {@code int} value represented by this
4.750 + * {@code Integer} object.
4.751 + */
4.752 + public int hashCode() {
4.753 + return value;
4.754 + }
4.755 +
4.756 + /**
4.757 + * Compares this object to the specified object. The result is
4.758 + * {@code true} if and only if the argument is not
4.759 + * {@code null} and is an {@code Integer} object that
4.760 + * contains the same {@code int} value as this object.
4.761 + *
4.762 + * @param obj the object to compare with.
4.763 + * @return {@code true} if the objects are the same;
4.764 + * {@code false} otherwise.
4.765 + */
4.766 + public boolean equals(Object obj) {
4.767 + if (obj instanceof Integer) {
4.768 + return value == ((Integer)obj).intValue();
4.769 + }
4.770 + return false;
4.771 + }
4.772 +
4.773 + /**
4.774 + * Determines the integer value of the system property with the
4.775 + * specified name.
4.776 + *
4.777 + * <p>The first argument is treated as the name of a system property.
4.778 + * System properties are accessible through the
4.779 + * {@link java.lang.System#getProperty(java.lang.String)} method. The
4.780 + * string value of this property is then interpreted as an integer
4.781 + * value and an {@code Integer} object representing this value is
4.782 + * returned. Details of possible numeric formats can be found with
4.783 + * the definition of {@code getProperty}.
4.784 + *
4.785 + * <p>If there is no property with the specified name, if the specified name
4.786 + * is empty or {@code null}, or if the property does not have
4.787 + * the correct numeric format, then {@code null} is returned.
4.788 + *
4.789 + * <p>In other words, this method returns an {@code Integer}
4.790 + * object equal to the value of:
4.791 + *
4.792 + * <blockquote>
4.793 + * {@code getInteger(nm, null)}
4.794 + * </blockquote>
4.795 + *
4.796 + * @param nm property name.
4.797 + * @return the {@code Integer} value of the property.
4.798 + * @see java.lang.System#getProperty(java.lang.String)
4.799 + * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
4.800 + */
4.801 + public static Integer getInteger(String nm) {
4.802 + return getInteger(nm, null);
4.803 + }
4.804 +
4.805 + /**
4.806 + * Determines the integer value of the system property with the
4.807 + * specified name.
4.808 + *
4.809 + * <p>The first argument is treated as the name of a system property.
4.810 + * System properties are accessible through the {@link
4.811 + * java.lang.System#getProperty(java.lang.String)} method. The
4.812 + * string value of this property is then interpreted as an integer
4.813 + * value and an {@code Integer} object representing this value is
4.814 + * returned. Details of possible numeric formats can be found with
4.815 + * the definition of {@code getProperty}.
4.816 + *
4.817 + * <p>The second argument is the default value. An {@code Integer} object
4.818 + * that represents the value of the second argument is returned if there
4.819 + * is no property of the specified name, if the property does not have
4.820 + * the correct numeric format, or if the specified name is empty or
4.821 + * {@code null}.
4.822 + *
4.823 + * <p>In other words, this method returns an {@code Integer} object
4.824 + * equal to the value of:
4.825 + *
4.826 + * <blockquote>
4.827 + * {@code getInteger(nm, new Integer(val))}
4.828 + * </blockquote>
4.829 + *
4.830 + * but in practice it may be implemented in a manner such as:
4.831 + *
4.832 + * <blockquote><pre>
4.833 + * Integer result = getInteger(nm, null);
4.834 + * return (result == null) ? new Integer(val) : result;
4.835 + * </pre></blockquote>
4.836 + *
4.837 + * to avoid the unnecessary allocation of an {@code Integer}
4.838 + * object when the default value is not needed.
4.839 + *
4.840 + * @param nm property name.
4.841 + * @param val default value.
4.842 + * @return the {@code Integer} value of the property.
4.843 + * @see java.lang.System#getProperty(java.lang.String)
4.844 + * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
4.845 + */
4.846 + public static Integer getInteger(String nm, int val) {
4.847 + Integer result = getInteger(nm, null);
4.848 + return (result == null) ? Integer.valueOf(val) : result;
4.849 + }
4.850 +
4.851 + /**
4.852 + * Returns the integer value of the system property with the
4.853 + * specified name. The first argument is treated as the name of a
4.854 + * system property. System properties are accessible through the
4.855 + * {@link java.lang.System#getProperty(java.lang.String)} method.
4.856 + * The string value of this property is then interpreted as an
4.857 + * integer value, as per the {@code Integer.decode} method,
4.858 + * and an {@code Integer} object representing this value is
4.859 + * returned.
4.860 + *
4.861 + * <ul><li>If the property value begins with the two ASCII characters
4.862 + * {@code 0x} or the ASCII character {@code #}, not
4.863 + * followed by a minus sign, then the rest of it is parsed as a
4.864 + * hexadecimal integer exactly as by the method
4.865 + * {@link #valueOf(java.lang.String, int)} with radix 16.
4.866 + * <li>If the property value begins with the ASCII character
4.867 + * {@code 0} followed by another character, it is parsed as an
4.868 + * octal integer exactly as by the method
4.869 + * {@link #valueOf(java.lang.String, int)} with radix 8.
4.870 + * <li>Otherwise, the property value is parsed as a decimal integer
4.871 + * exactly as by the method {@link #valueOf(java.lang.String, int)}
4.872 + * with radix 10.
4.873 + * </ul>
4.874 + *
4.875 + * <p>The second argument is the default value. The default value is
4.876 + * returned if there is no property of the specified name, if the
4.877 + * property does not have the correct numeric format, or if the
4.878 + * specified name is empty or {@code null}.
4.879 + *
4.880 + * @param nm property name.
4.881 + * @param val default value.
4.882 + * @return the {@code Integer} value of the property.
4.883 + * @see java.lang.System#getProperty(java.lang.String)
4.884 + * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
4.885 + * @see java.lang.Integer#decode
4.886 + */
4.887 + public static Integer getInteger(String nm, Integer val) {
4.888 + String v = null;
4.889 + try {
4.890 + v = System.getProperty(nm);
4.891 + } catch (IllegalArgumentException e) {
4.892 + } catch (NullPointerException e) {
4.893 + }
4.894 + if (v != null) {
4.895 + try {
4.896 + return Integer.decode(v);
4.897 + } catch (NumberFormatException e) {
4.898 + }
4.899 + }
4.900 + return val;
4.901 + }
4.902 +
4.903 + /**
4.904 + * Decodes a {@code String} into an {@code Integer}.
4.905 + * Accepts decimal, hexadecimal, and octal numbers given
4.906 + * by the following grammar:
4.907 + *
4.908 + * <blockquote>
4.909 + * <dl>
4.910 + * <dt><i>DecodableString:</i>
4.911 + * <dd><i>Sign<sub>opt</sub> DecimalNumeral</i>
4.912 + * <dd><i>Sign<sub>opt</sub></i> {@code 0x} <i>HexDigits</i>
4.913 + * <dd><i>Sign<sub>opt</sub></i> {@code 0X} <i>HexDigits</i>
4.914 + * <dd><i>Sign<sub>opt</sub></i> {@code #} <i>HexDigits</i>
4.915 + * <dd><i>Sign<sub>opt</sub></i> {@code 0} <i>OctalDigits</i>
4.916 + * <p>
4.917 + * <dt><i>Sign:</i>
4.918 + * <dd>{@code -}
4.919 + * <dd>{@code +}
4.920 + * </dl>
4.921 + * </blockquote>
4.922 + *
4.923 + * <i>DecimalNumeral</i>, <i>HexDigits</i>, and <i>OctalDigits</i>
4.924 + * are as defined in section 3.10.1 of
4.925 + * <cite>The Java™ Language Specification</cite>,
4.926 + * except that underscores are not accepted between digits.
4.927 + *
4.928 + * <p>The sequence of characters following an optional
4.929 + * sign and/or radix specifier ("{@code 0x}", "{@code 0X}",
4.930 + * "{@code #}", or leading zero) is parsed as by the {@code
4.931 + * Integer.parseInt} method with the indicated radix (10, 16, or
4.932 + * 8). This sequence of characters must represent a positive
4.933 + * value or a {@link NumberFormatException} will be thrown. The
4.934 + * result is negated if first character of the specified {@code
4.935 + * String} is the minus sign. No whitespace characters are
4.936 + * permitted in the {@code String}.
4.937 + *
4.938 + * @param nm the {@code String} to decode.
4.939 + * @return an {@code Integer} object holding the {@code int}
4.940 + * value represented by {@code nm}
4.941 + * @exception NumberFormatException if the {@code String} does not
4.942 + * contain a parsable integer.
4.943 + * @see java.lang.Integer#parseInt(java.lang.String, int)
4.944 + */
4.945 + public static Integer decode(String nm) throws NumberFormatException {
4.946 + int radix = 10;
4.947 + int index = 0;
4.948 + boolean negative = false;
4.949 + Integer result;
4.950 +
4.951 + if (nm.length() == 0)
4.952 + throw new NumberFormatException("Zero length string");
4.953 + char firstChar = nm.charAt(0);
4.954 + // Handle sign, if present
4.955 + if (firstChar == '-') {
4.956 + negative = true;
4.957 + index++;
4.958 + } else if (firstChar == '+')
4.959 + index++;
4.960 +
4.961 + // Handle radix specifier, if present
4.962 + if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
4.963 + index += 2;
4.964 + radix = 16;
4.965 + }
4.966 + else if (nm.startsWith("#", index)) {
4.967 + index ++;
4.968 + radix = 16;
4.969 + }
4.970 + else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
4.971 + index ++;
4.972 + radix = 8;
4.973 + }
4.974 +
4.975 + if (nm.startsWith("-", index) || nm.startsWith("+", index))
4.976 + throw new NumberFormatException("Sign character in wrong position");
4.977 +
4.978 + try {
4.979 + result = Integer.valueOf(nm.substring(index), radix);
4.980 + result = negative ? Integer.valueOf(-result.intValue()) : result;
4.981 + } catch (NumberFormatException e) {
4.982 + // If number is Integer.MIN_VALUE, we'll end up here. The next line
4.983 + // handles this case, and causes any genuine format error to be
4.984 + // rethrown.
4.985 + String constant = negative ? ("-" + nm.substring(index))
4.986 + : nm.substring(index);
4.987 + result = Integer.valueOf(constant, radix);
4.988 + }
4.989 + return result;
4.990 + }
4.991 +
4.992 + /**
4.993 + * Compares two {@code Integer} objects numerically.
4.994 + *
4.995 + * @param anotherInteger the {@code Integer} to be compared.
4.996 + * @return the value {@code 0} if this {@code Integer} is
4.997 + * equal to the argument {@code Integer}; a value less than
4.998 + * {@code 0} if this {@code Integer} is numerically less
4.999 + * than the argument {@code Integer}; and a value greater
4.1000 + * than {@code 0} if this {@code Integer} is numerically
4.1001 + * greater than the argument {@code Integer} (signed
4.1002 + * comparison).
4.1003 + * @since 1.2
4.1004 + */
4.1005 + public int compareTo(Integer anotherInteger) {
4.1006 + return compare(this.value, anotherInteger.value);
4.1007 + }
4.1008 +
4.1009 + /**
4.1010 + * Compares two {@code int} values numerically.
4.1011 + * The value returned is identical to what would be returned by:
4.1012 + * <pre>
4.1013 + * Integer.valueOf(x).compareTo(Integer.valueOf(y))
4.1014 + * </pre>
4.1015 + *
4.1016 + * @param x the first {@code int} to compare
4.1017 + * @param y the second {@code int} to compare
4.1018 + * @return the value {@code 0} if {@code x == y};
4.1019 + * a value less than {@code 0} if {@code x < y}; and
4.1020 + * a value greater than {@code 0} if {@code x > y}
4.1021 + * @since 1.7
4.1022 + */
4.1023 + public static int compare(int x, int y) {
4.1024 + return (x < y) ? -1 : ((x == y) ? 0 : 1);
4.1025 + }
4.1026 +
4.1027 +
4.1028 + // Bit twiddling
4.1029 +
4.1030 + /**
4.1031 + * The number of bits used to represent an {@code int} value in two's
4.1032 + * complement binary form.
4.1033 + *
4.1034 + * @since 1.5
4.1035 + */
4.1036 + public static final int SIZE = 32;
4.1037 +
4.1038 + /**
4.1039 + * Returns an {@code int} value with at most a single one-bit, in the
4.1040 + * position of the highest-order ("leftmost") one-bit in the specified
4.1041 + * {@code int} value. Returns zero if the specified value has no
4.1042 + * one-bits in its two's complement binary representation, that is, if it
4.1043 + * is equal to zero.
4.1044 + *
4.1045 + * @return an {@code int} value with a single one-bit, in the position
4.1046 + * of the highest-order one-bit in the specified value, or zero if
4.1047 + * the specified value is itself equal to zero.
4.1048 + * @since 1.5
4.1049 + */
4.1050 + public static int highestOneBit(int i) {
4.1051 + // HD, Figure 3-1
4.1052 + i |= (i >> 1);
4.1053 + i |= (i >> 2);
4.1054 + i |= (i >> 4);
4.1055 + i |= (i >> 8);
4.1056 + i |= (i >> 16);
4.1057 + return i - (i >>> 1);
4.1058 + }
4.1059 +
4.1060 + /**
4.1061 + * Returns an {@code int} value with at most a single one-bit, in the
4.1062 + * position of the lowest-order ("rightmost") one-bit in the specified
4.1063 + * {@code int} value. Returns zero if the specified value has no
4.1064 + * one-bits in its two's complement binary representation, that is, if it
4.1065 + * is equal to zero.
4.1066 + *
4.1067 + * @return an {@code int} value with a single one-bit, in the position
4.1068 + * of the lowest-order one-bit in the specified value, or zero if
4.1069 + * the specified value is itself equal to zero.
4.1070 + * @since 1.5
4.1071 + */
4.1072 + public static int lowestOneBit(int i) {
4.1073 + // HD, Section 2-1
4.1074 + return i & -i;
4.1075 + }
4.1076 +
4.1077 + /**
4.1078 + * Returns the number of zero bits preceding the highest-order
4.1079 + * ("leftmost") one-bit in the two's complement binary representation
4.1080 + * of the specified {@code int} value. Returns 32 if the
4.1081 + * specified value has no one-bits in its two's complement representation,
4.1082 + * in other words if it is equal to zero.
4.1083 + *
4.1084 + * <p>Note that this method is closely related to the logarithm base 2.
4.1085 + * For all positive {@code int} values x:
4.1086 + * <ul>
4.1087 + * <li>floor(log<sub>2</sub>(x)) = {@code 31 - numberOfLeadingZeros(x)}
4.1088 + * <li>ceil(log<sub>2</sub>(x)) = {@code 32 - numberOfLeadingZeros(x - 1)}
4.1089 + * </ul>
4.1090 + *
4.1091 + * @return the number of zero bits preceding the highest-order
4.1092 + * ("leftmost") one-bit in the two's complement binary representation
4.1093 + * of the specified {@code int} value, or 32 if the value
4.1094 + * is equal to zero.
4.1095 + * @since 1.5
4.1096 + */
4.1097 + public static int numberOfLeadingZeros(int i) {
4.1098 + // HD, Figure 5-6
4.1099 + if (i == 0)
4.1100 + return 32;
4.1101 + int n = 1;
4.1102 + if (i >>> 16 == 0) { n += 16; i <<= 16; }
4.1103 + if (i >>> 24 == 0) { n += 8; i <<= 8; }
4.1104 + if (i >>> 28 == 0) { n += 4; i <<= 4; }
4.1105 + if (i >>> 30 == 0) { n += 2; i <<= 2; }
4.1106 + n -= i >>> 31;
4.1107 + return n;
4.1108 + }
4.1109 +
4.1110 + /**
4.1111 + * Returns the number of zero bits following the lowest-order ("rightmost")
4.1112 + * one-bit in the two's complement binary representation of the specified
4.1113 + * {@code int} value. Returns 32 if the specified value has no
4.1114 + * one-bits in its two's complement representation, in other words if it is
4.1115 + * equal to zero.
4.1116 + *
4.1117 + * @return the number of zero bits following the lowest-order ("rightmost")
4.1118 + * one-bit in the two's complement binary representation of the
4.1119 + * specified {@code int} value, or 32 if the value is equal
4.1120 + * to zero.
4.1121 + * @since 1.5
4.1122 + */
4.1123 + public static int numberOfTrailingZeros(int i) {
4.1124 + // HD, Figure 5-14
4.1125 + int y;
4.1126 + if (i == 0) return 32;
4.1127 + int n = 31;
4.1128 + y = i <<16; if (y != 0) { n = n -16; i = y; }
4.1129 + y = i << 8; if (y != 0) { n = n - 8; i = y; }
4.1130 + y = i << 4; if (y != 0) { n = n - 4; i = y; }
4.1131 + y = i << 2; if (y != 0) { n = n - 2; i = y; }
4.1132 + return n - ((i << 1) >>> 31);
4.1133 + }
4.1134 +
4.1135 + /**
4.1136 + * Returns the number of one-bits in the two's complement binary
4.1137 + * representation of the specified {@code int} value. This function is
4.1138 + * sometimes referred to as the <i>population count</i>.
4.1139 + *
4.1140 + * @return the number of one-bits in the two's complement binary
4.1141 + * representation of the specified {@code int} value.
4.1142 + * @since 1.5
4.1143 + */
4.1144 + public static int bitCount(int i) {
4.1145 + // HD, Figure 5-2
4.1146 + i = i - ((i >>> 1) & 0x55555555);
4.1147 + i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
4.1148 + i = (i + (i >>> 4)) & 0x0f0f0f0f;
4.1149 + i = i + (i >>> 8);
4.1150 + i = i + (i >>> 16);
4.1151 + return i & 0x3f;
4.1152 + }
4.1153 +
4.1154 + /**
4.1155 + * Returns the value obtained by rotating the two's complement binary
4.1156 + * representation of the specified {@code int} value left by the
4.1157 + * specified number of bits. (Bits shifted out of the left hand, or
4.1158 + * high-order, side reenter on the right, or low-order.)
4.1159 + *
4.1160 + * <p>Note that left rotation with a negative distance is equivalent to
4.1161 + * right rotation: {@code rotateLeft(val, -distance) == rotateRight(val,
4.1162 + * distance)}. Note also that rotation by any multiple of 32 is a
4.1163 + * no-op, so all but the last five bits of the rotation distance can be
4.1164 + * ignored, even if the distance is negative: {@code rotateLeft(val,
4.1165 + * distance) == rotateLeft(val, distance & 0x1F)}.
4.1166 + *
4.1167 + * @return the value obtained by rotating the two's complement binary
4.1168 + * representation of the specified {@code int} value left by the
4.1169 + * specified number of bits.
4.1170 + * @since 1.5
4.1171 + */
4.1172 + public static int rotateLeft(int i, int distance) {
4.1173 + return (i << distance) | (i >>> -distance);
4.1174 + }
4.1175 +
4.1176 + /**
4.1177 + * Returns the value obtained by rotating the two's complement binary
4.1178 + * representation of the specified {@code int} value right by the
4.1179 + * specified number of bits. (Bits shifted out of the right hand, or
4.1180 + * low-order, side reenter on the left, or high-order.)
4.1181 + *
4.1182 + * <p>Note that right rotation with a negative distance is equivalent to
4.1183 + * left rotation: {@code rotateRight(val, -distance) == rotateLeft(val,
4.1184 + * distance)}. Note also that rotation by any multiple of 32 is a
4.1185 + * no-op, so all but the last five bits of the rotation distance can be
4.1186 + * ignored, even if the distance is negative: {@code rotateRight(val,
4.1187 + * distance) == rotateRight(val, distance & 0x1F)}.
4.1188 + *
4.1189 + * @return the value obtained by rotating the two's complement binary
4.1190 + * representation of the specified {@code int} value right by the
4.1191 + * specified number of bits.
4.1192 + * @since 1.5
4.1193 + */
4.1194 + public static int rotateRight(int i, int distance) {
4.1195 + return (i >>> distance) | (i << -distance);
4.1196 + }
4.1197 +
4.1198 + /**
4.1199 + * Returns the value obtained by reversing the order of the bits in the
4.1200 + * two's complement binary representation of the specified {@code int}
4.1201 + * value.
4.1202 + *
4.1203 + * @return the value obtained by reversing order of the bits in the
4.1204 + * specified {@code int} value.
4.1205 + * @since 1.5
4.1206 + */
4.1207 + public static int reverse(int i) {
4.1208 + // HD, Figure 7-1
4.1209 + i = (i & 0x55555555) << 1 | (i >>> 1) & 0x55555555;
4.1210 + i = (i & 0x33333333) << 2 | (i >>> 2) & 0x33333333;
4.1211 + i = (i & 0x0f0f0f0f) << 4 | (i >>> 4) & 0x0f0f0f0f;
4.1212 + i = (i << 24) | ((i & 0xff00) << 8) |
4.1213 + ((i >>> 8) & 0xff00) | (i >>> 24);
4.1214 + return i;
4.1215 + }
4.1216 +
4.1217 + /**
4.1218 + * Returns the signum function of the specified {@code int} value. (The
4.1219 + * return value is -1 if the specified value is negative; 0 if the
4.1220 + * specified value is zero; and 1 if the specified value is positive.)
4.1221 + *
4.1222 + * @return the signum function of the specified {@code int} value.
4.1223 + * @since 1.5
4.1224 + */
4.1225 + public static int signum(int i) {
4.1226 + // HD, Section 2-7
4.1227 + return (i >> 31) | (-i >>> 31);
4.1228 + }
4.1229 +
4.1230 + /**
4.1231 + * Returns the value obtained by reversing the order of the bytes in the
4.1232 + * two's complement representation of the specified {@code int} value.
4.1233 + *
4.1234 + * @return the value obtained by reversing the bytes in the specified
4.1235 + * {@code int} value.
4.1236 + * @since 1.5
4.1237 + */
4.1238 + public static int reverseBytes(int i) {
4.1239 + return ((i >>> 24) ) |
4.1240 + ((i >> 8) & 0xFF00) |
4.1241 + ((i << 8) & 0xFF0000) |
4.1242 + ((i << 24));
4.1243 + }
4.1244 +
4.1245 + /** use serialVersionUID from JDK 1.0.2 for interoperability */
4.1246 + private static final long serialVersionUID = 1360826667806852920L;
4.1247 +}
5.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
5.2 +++ b/emul/src/main/java/java/lang/InterruptedException.java Fri Sep 28 17:59:03 2012 +0200
5.3 @@ -0,0 +1,69 @@
5.4 +/*
5.5 + * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
5.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5.7 + *
5.8 + * This code is free software; you can redistribute it and/or modify it
5.9 + * under the terms of the GNU General Public License version 2 only, as
5.10 + * published by the Free Software Foundation. Oracle designates this
5.11 + * particular file as subject to the "Classpath" exception as provided
5.12 + * by Oracle in the LICENSE file that accompanied this code.
5.13 + *
5.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
5.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
5.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
5.17 + * version 2 for more details (a copy is included in the LICENSE file that
5.18 + * accompanied this code).
5.19 + *
5.20 + * You should have received a copy of the GNU General Public License version
5.21 + * 2 along with this work; if not, write to the Free Software Foundation,
5.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
5.23 + *
5.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
5.25 + * or visit www.oracle.com if you need additional information or have any
5.26 + * questions.
5.27 + */
5.28 +
5.29 +package java.lang;
5.30 +
5.31 +/**
5.32 + * Thrown when a thread is waiting, sleeping, or otherwise occupied,
5.33 + * and the thread is interrupted, either before or during the activity.
5.34 + * Occasionally a method may wish to test whether the current
5.35 + * thread has been interrupted, and if so, to immediately throw
5.36 + * this exception. The following code can be used to achieve
5.37 + * this effect:
5.38 + * <pre>
5.39 + * if (Thread.interrupted()) // Clears interrupted status!
5.40 + * throw new InterruptedException();
5.41 + * </pre>
5.42 + *
5.43 + * @author Frank Yellin
5.44 + * @see java.lang.Object#wait()
5.45 + * @see java.lang.Object#wait(long)
5.46 + * @see java.lang.Object#wait(long, int)
5.47 + * @see java.lang.Thread#sleep(long)
5.48 + * @see java.lang.Thread#interrupt()
5.49 + * @see java.lang.Thread#interrupted()
5.50 + * @since JDK1.0
5.51 + */
5.52 +public
5.53 +class InterruptedException extends Exception {
5.54 + private static final long serialVersionUID = 6700697376100628473L;
5.55 +
5.56 + /**
5.57 + * Constructs an <code>InterruptedException</code> with no detail message.
5.58 + */
5.59 + public InterruptedException() {
5.60 + super();
5.61 + }
5.62 +
5.63 + /**
5.64 + * Constructs an <code>InterruptedException</code> with the
5.65 + * specified detail message.
5.66 + *
5.67 + * @param s the detail message.
5.68 + */
5.69 + public InterruptedException(String s) {
5.70 + super(s);
5.71 + }
5.72 +}
6.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
6.2 +++ b/emul/src/main/java/java/lang/Number.java Fri Sep 28 17:59:03 2012 +0200
6.3 @@ -0,0 +1,112 @@
6.4 +/*
6.5 + * Copyright (c) 1994, 2001, Oracle and/or its affiliates. All rights reserved.
6.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6.7 + *
6.8 + * This code is free software; you can redistribute it and/or modify it
6.9 + * under the terms of the GNU General Public License version 2 only, as
6.10 + * published by the Free Software Foundation. Oracle designates this
6.11 + * particular file as subject to the "Classpath" exception as provided
6.12 + * by Oracle in the LICENSE file that accompanied this code.
6.13 + *
6.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
6.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
6.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
6.17 + * version 2 for more details (a copy is included in the LICENSE file that
6.18 + * accompanied this code).
6.19 + *
6.20 + * You should have received a copy of the GNU General Public License version
6.21 + * 2 along with this work; if not, write to the Free Software Foundation,
6.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
6.23 + *
6.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
6.25 + * or visit www.oracle.com if you need additional information or have any
6.26 + * questions.
6.27 + */
6.28 +
6.29 +package java.lang;
6.30 +
6.31 +/**
6.32 + * The abstract class <code>Number</code> is the superclass of classes
6.33 + * <code>BigDecimal</code>, <code>BigInteger</code>,
6.34 + * <code>Byte</code>, <code>Double</code>, <code>Float</code>,
6.35 + * <code>Integer</code>, <code>Long</code>, and <code>Short</code>.
6.36 + * <p>
6.37 + * Subclasses of <code>Number</code> must provide methods to convert
6.38 + * the represented numeric value to <code>byte</code>, <code>double</code>,
6.39 + * <code>float</code>, <code>int</code>, <code>long</code>, and
6.40 + * <code>short</code>.
6.41 + *
6.42 + * @author Lee Boynton
6.43 + * @author Arthur van Hoff
6.44 + * @see java.lang.Byte
6.45 + * @see java.lang.Double
6.46 + * @see java.lang.Float
6.47 + * @see java.lang.Integer
6.48 + * @see java.lang.Long
6.49 + * @see java.lang.Short
6.50 + * @since JDK1.0
6.51 + */
6.52 +public abstract class Number implements java.io.Serializable {
6.53 + /**
6.54 + * Returns the value of the specified number as an <code>int</code>.
6.55 + * This may involve rounding or truncation.
6.56 + *
6.57 + * @return the numeric value represented by this object after conversion
6.58 + * to type <code>int</code>.
6.59 + */
6.60 + public abstract int intValue();
6.61 +
6.62 + /**
6.63 + * Returns the value of the specified number as a <code>long</code>.
6.64 + * This may involve rounding or truncation.
6.65 + *
6.66 + * @return the numeric value represented by this object after conversion
6.67 + * to type <code>long</code>.
6.68 + */
6.69 + public abstract long longValue();
6.70 +
6.71 + /**
6.72 + * Returns the value of the specified number as a <code>float</code>.
6.73 + * This may involve rounding.
6.74 + *
6.75 + * @return the numeric value represented by this object after conversion
6.76 + * to type <code>float</code>.
6.77 + */
6.78 + public abstract float floatValue();
6.79 +
6.80 + /**
6.81 + * Returns the value of the specified number as a <code>double</code>.
6.82 + * This may involve rounding.
6.83 + *
6.84 + * @return the numeric value represented by this object after conversion
6.85 + * to type <code>double</code>.
6.86 + */
6.87 + public abstract double doubleValue();
6.88 +
6.89 + /**
6.90 + * Returns the value of the specified number as a <code>byte</code>.
6.91 + * This may involve rounding or truncation.
6.92 + *
6.93 + * @return the numeric value represented by this object after conversion
6.94 + * to type <code>byte</code>.
6.95 + * @since JDK1.1
6.96 + */
6.97 + public byte byteValue() {
6.98 + return (byte)intValue();
6.99 + }
6.100 +
6.101 + /**
6.102 + * Returns the value of the specified number as a <code>short</code>.
6.103 + * This may involve rounding or truncation.
6.104 + *
6.105 + * @return the numeric value represented by this object after conversion
6.106 + * to type <code>short</code>.
6.107 + * @since JDK1.1
6.108 + */
6.109 + public short shortValue() {
6.110 + return (short)intValue();
6.111 + }
6.112 +
6.113 + /** use serialVersionUID from JDK 1.0.2 for interoperability */
6.114 + private static final long serialVersionUID = -8742448824652078965L;
6.115 +}
7.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
7.2 +++ b/emul/src/main/java/java/lang/Object.java Fri Sep 28 17:59:03 2012 +0200
7.3 @@ -0,0 +1,554 @@
7.4 +/*
7.5 + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
7.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7.7 + *
7.8 + * This code is free software; you can redistribute it and/or modify it
7.9 + * under the terms of the GNU General Public License version 2 only, as
7.10 + * published by the Free Software Foundation. Oracle designates this
7.11 + * particular file as subject to the "Classpath" exception as provided
7.12 + * by Oracle in the LICENSE file that accompanied this code.
7.13 + *
7.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
7.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
7.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
7.17 + * version 2 for more details (a copy is included in the LICENSE file that
7.18 + * accompanied this code).
7.19 + *
7.20 + * You should have received a copy of the GNU General Public License version
7.21 + * 2 along with this work; if not, write to the Free Software Foundation,
7.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
7.23 + *
7.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
7.25 + * or visit www.oracle.com if you need additional information or have any
7.26 + * questions.
7.27 + */
7.28 +
7.29 +package java.lang;
7.30 +
7.31 +/**
7.32 + * Class {@code Object} is the root of the class hierarchy.
7.33 + * Every class has {@code Object} as a superclass. All objects,
7.34 + * including arrays, implement the methods of this class.
7.35 + *
7.36 + * @author unascribed
7.37 + * @see java.lang.Class
7.38 + * @since JDK1.0
7.39 + */
7.40 +public class Object {
7.41 +
7.42 + private static native void registerNatives();
7.43 + static {
7.44 + registerNatives();
7.45 + }
7.46 +
7.47 + /**
7.48 + * Returns the runtime class of this {@code Object}. The returned
7.49 + * {@code Class} object is the object that is locked by {@code
7.50 + * static synchronized} methods of the represented class.
7.51 + *
7.52 + * <p><b>The actual result type is {@code Class<? extends |X|>}
7.53 + * where {@code |X|} is the erasure of the static type of the
7.54 + * expression on which {@code getClass} is called.</b> For
7.55 + * example, no cast is required in this code fragment:</p>
7.56 + *
7.57 + * <p>
7.58 + * {@code Number n = 0; }<br>
7.59 + * {@code Class<? extends Number> c = n.getClass(); }
7.60 + * </p>
7.61 + *
7.62 + * @return The {@code Class} object that represents the runtime
7.63 + * class of this object.
7.64 + * @see Class Literals, section 15.8.2 of
7.65 + * <cite>The Java™ Language Specification</cite>.
7.66 + */
7.67 + public final native Class<?> getClass();
7.68 +
7.69 + /**
7.70 + * Returns a hash code value for the object. This method is
7.71 + * supported for the benefit of hash tables such as those provided by
7.72 + * {@link java.util.HashMap}.
7.73 + * <p>
7.74 + * The general contract of {@code hashCode} is:
7.75 + * <ul>
7.76 + * <li>Whenever it is invoked on the same object more than once during
7.77 + * an execution of a Java application, the {@code hashCode} method
7.78 + * must consistently return the same integer, provided no information
7.79 + * used in {@code equals} comparisons on the object is modified.
7.80 + * This integer need not remain consistent from one execution of an
7.81 + * application to another execution of the same application.
7.82 + * <li>If two objects are equal according to the {@code equals(Object)}
7.83 + * method, then calling the {@code hashCode} method on each of
7.84 + * the two objects must produce the same integer result.
7.85 + * <li>It is <em>not</em> required that if two objects are unequal
7.86 + * according to the {@link java.lang.Object#equals(java.lang.Object)}
7.87 + * method, then calling the {@code hashCode} method on each of the
7.88 + * two objects must produce distinct integer results. However, the
7.89 + * programmer should be aware that producing distinct integer results
7.90 + * for unequal objects may improve the performance of hash tables.
7.91 + * </ul>
7.92 + * <p>
7.93 + * As much as is reasonably practical, the hashCode method defined by
7.94 + * class {@code Object} does return distinct integers for distinct
7.95 + * objects. (This is typically implemented by converting the internal
7.96 + * address of the object into an integer, but this implementation
7.97 + * technique is not required by the
7.98 + * Java<font size="-2"><sup>TM</sup></font> programming language.)
7.99 + *
7.100 + * @return a hash code value for this object.
7.101 + * @see java.lang.Object#equals(java.lang.Object)
7.102 + * @see java.lang.System#identityHashCode
7.103 + */
7.104 + public native int hashCode();
7.105 +
7.106 + /**
7.107 + * Indicates whether some other object is "equal to" this one.
7.108 + * <p>
7.109 + * The {@code equals} method implements an equivalence relation
7.110 + * on non-null object references:
7.111 + * <ul>
7.112 + * <li>It is <i>reflexive</i>: for any non-null reference value
7.113 + * {@code x}, {@code x.equals(x)} should return
7.114 + * {@code true}.
7.115 + * <li>It is <i>symmetric</i>: for any non-null reference values
7.116 + * {@code x} and {@code y}, {@code x.equals(y)}
7.117 + * should return {@code true} if and only if
7.118 + * {@code y.equals(x)} returns {@code true}.
7.119 + * <li>It is <i>transitive</i>: for any non-null reference values
7.120 + * {@code x}, {@code y}, and {@code z}, if
7.121 + * {@code x.equals(y)} returns {@code true} and
7.122 + * {@code y.equals(z)} returns {@code true}, then
7.123 + * {@code x.equals(z)} should return {@code true}.
7.124 + * <li>It is <i>consistent</i>: for any non-null reference values
7.125 + * {@code x} and {@code y}, multiple invocations of
7.126 + * {@code x.equals(y)} consistently return {@code true}
7.127 + * or consistently return {@code false}, provided no
7.128 + * information used in {@code equals} comparisons on the
7.129 + * objects is modified.
7.130 + * <li>For any non-null reference value {@code x},
7.131 + * {@code x.equals(null)} should return {@code false}.
7.132 + * </ul>
7.133 + * <p>
7.134 + * The {@code equals} method for class {@code Object} implements
7.135 + * the most discriminating possible equivalence relation on objects;
7.136 + * that is, for any non-null reference values {@code x} and
7.137 + * {@code y}, this method returns {@code true} if and only
7.138 + * if {@code x} and {@code y} refer to the same object
7.139 + * ({@code x == y} has the value {@code true}).
7.140 + * <p>
7.141 + * Note that it is generally necessary to override the {@code hashCode}
7.142 + * method whenever this method is overridden, so as to maintain the
7.143 + * general contract for the {@code hashCode} method, which states
7.144 + * that equal objects must have equal hash codes.
7.145 + *
7.146 + * @param obj the reference object with which to compare.
7.147 + * @return {@code true} if this object is the same as the obj
7.148 + * argument; {@code false} otherwise.
7.149 + * @see #hashCode()
7.150 + * @see java.util.HashMap
7.151 + */
7.152 + public boolean equals(Object obj) {
7.153 + return (this == obj);
7.154 + }
7.155 +
7.156 + /**
7.157 + * Creates and returns a copy of this object. The precise meaning
7.158 + * of "copy" may depend on the class of the object. The general
7.159 + * intent is that, for any object {@code x}, the expression:
7.160 + * <blockquote>
7.161 + * <pre>
7.162 + * x.clone() != x</pre></blockquote>
7.163 + * will be true, and that the expression:
7.164 + * <blockquote>
7.165 + * <pre>
7.166 + * x.clone().getClass() == x.getClass()</pre></blockquote>
7.167 + * will be {@code true}, but these are not absolute requirements.
7.168 + * While it is typically the case that:
7.169 + * <blockquote>
7.170 + * <pre>
7.171 + * x.clone().equals(x)</pre></blockquote>
7.172 + * will be {@code true}, this is not an absolute requirement.
7.173 + * <p>
7.174 + * By convention, the returned object should be obtained by calling
7.175 + * {@code super.clone}. If a class and all of its superclasses (except
7.176 + * {@code Object}) obey this convention, it will be the case that
7.177 + * {@code x.clone().getClass() == x.getClass()}.
7.178 + * <p>
7.179 + * By convention, the object returned by this method should be independent
7.180 + * of this object (which is being cloned). To achieve this independence,
7.181 + * it may be necessary to modify one or more fields of the object returned
7.182 + * by {@code super.clone} before returning it. Typically, this means
7.183 + * copying any mutable objects that comprise the internal "deep structure"
7.184 + * of the object being cloned and replacing the references to these
7.185 + * objects with references to the copies. If a class contains only
7.186 + * primitive fields or references to immutable objects, then it is usually
7.187 + * the case that no fields in the object returned by {@code super.clone}
7.188 + * need to be modified.
7.189 + * <p>
7.190 + * The method {@code clone} for class {@code Object} performs a
7.191 + * specific cloning operation. First, if the class of this object does
7.192 + * not implement the interface {@code Cloneable}, then a
7.193 + * {@code CloneNotSupportedException} is thrown. Note that all arrays
7.194 + * are considered to implement the interface {@code Cloneable} and that
7.195 + * the return type of the {@code clone} method of an array type {@code T[]}
7.196 + * is {@code T[]} where T is any reference or primitive type.
7.197 + * Otherwise, this method creates a new instance of the class of this
7.198 + * object and initializes all its fields with exactly the contents of
7.199 + * the corresponding fields of this object, as if by assignment; the
7.200 + * contents of the fields are not themselves cloned. Thus, this method
7.201 + * performs a "shallow copy" of this object, not a "deep copy" operation.
7.202 + * <p>
7.203 + * The class {@code Object} does not itself implement the interface
7.204 + * {@code Cloneable}, so calling the {@code clone} method on an object
7.205 + * whose class is {@code Object} will result in throwing an
7.206 + * exception at run time.
7.207 + *
7.208 + * @return a clone of this instance.
7.209 + * @exception CloneNotSupportedException if the object's class does not
7.210 + * support the {@code Cloneable} interface. Subclasses
7.211 + * that override the {@code clone} method can also
7.212 + * throw this exception to indicate that an instance cannot
7.213 + * be cloned.
7.214 + * @see java.lang.Cloneable
7.215 + */
7.216 + protected native Object clone() throws CloneNotSupportedException;
7.217 +
7.218 + /**
7.219 + * Returns a string representation of the object. In general, the
7.220 + * {@code toString} method returns a string that
7.221 + * "textually represents" this object. The result should
7.222 + * be a concise but informative representation that is easy for a
7.223 + * person to read.
7.224 + * It is recommended that all subclasses override this method.
7.225 + * <p>
7.226 + * The {@code toString} method for class {@code Object}
7.227 + * returns a string consisting of the name of the class of which the
7.228 + * object is an instance, the at-sign character `{@code @}', and
7.229 + * the unsigned hexadecimal representation of the hash code of the
7.230 + * object. In other words, this method returns a string equal to the
7.231 + * value of:
7.232 + * <blockquote>
7.233 + * <pre>
7.234 + * getClass().getName() + '@' + Integer.toHexString(hashCode())
7.235 + * </pre></blockquote>
7.236 + *
7.237 + * @return a string representation of the object.
7.238 + */
7.239 + public String toString() {
7.240 + return getClass().getName() + "@" + Integer.toHexString(hashCode());
7.241 + }
7.242 +
7.243 + /**
7.244 + * Wakes up a single thread that is waiting on this object's
7.245 + * monitor. If any threads are waiting on this object, one of them
7.246 + * is chosen to be awakened. The choice is arbitrary and occurs at
7.247 + * the discretion of the implementation. A thread waits on an object's
7.248 + * monitor by calling one of the {@code wait} methods.
7.249 + * <p>
7.250 + * The awakened thread will not be able to proceed until the current
7.251 + * thread relinquishes the lock on this object. The awakened thread will
7.252 + * compete in the usual manner with any other threads that might be
7.253 + * actively competing to synchronize on this object; for example, the
7.254 + * awakened thread enjoys no reliable privilege or disadvantage in being
7.255 + * the next thread to lock this object.
7.256 + * <p>
7.257 + * This method should only be called by a thread that is the owner
7.258 + * of this object's monitor. A thread becomes the owner of the
7.259 + * object's monitor in one of three ways:
7.260 + * <ul>
7.261 + * <li>By executing a synchronized instance method of that object.
7.262 + * <li>By executing the body of a {@code synchronized} statement
7.263 + * that synchronizes on the object.
7.264 + * <li>For objects of type {@code Class,} by executing a
7.265 + * synchronized static method of that class.
7.266 + * </ul>
7.267 + * <p>
7.268 + * Only one thread at a time can own an object's monitor.
7.269 + *
7.270 + * @exception IllegalMonitorStateException if the current thread is not
7.271 + * the owner of this object's monitor.
7.272 + * @see java.lang.Object#notifyAll()
7.273 + * @see java.lang.Object#wait()
7.274 + */
7.275 + public final native void notify();
7.276 +
7.277 + /**
7.278 + * Wakes up all threads that are waiting on this object's monitor. A
7.279 + * thread waits on an object's monitor by calling one of the
7.280 + * {@code wait} methods.
7.281 + * <p>
7.282 + * The awakened threads will not be able to proceed until the current
7.283 + * thread relinquishes the lock on this object. The awakened threads
7.284 + * will compete in the usual manner with any other threads that might
7.285 + * be actively competing to synchronize on this object; for example,
7.286 + * the awakened threads enjoy no reliable privilege or disadvantage in
7.287 + * being the next thread to lock this object.
7.288 + * <p>
7.289 + * This method should only be called by a thread that is the owner
7.290 + * of this object's monitor. See the {@code notify} method for a
7.291 + * description of the ways in which a thread can become the owner of
7.292 + * a monitor.
7.293 + *
7.294 + * @exception IllegalMonitorStateException if the current thread is not
7.295 + * the owner of this object's monitor.
7.296 + * @see java.lang.Object#notify()
7.297 + * @see java.lang.Object#wait()
7.298 + */
7.299 + public final native void notifyAll();
7.300 +
7.301 + /**
7.302 + * Causes the current thread to wait until either another thread invokes the
7.303 + * {@link java.lang.Object#notify()} method or the
7.304 + * {@link java.lang.Object#notifyAll()} method for this object, or a
7.305 + * specified amount of time has elapsed.
7.306 + * <p>
7.307 + * The current thread must own this object's monitor.
7.308 + * <p>
7.309 + * This method causes the current thread (call it <var>T</var>) to
7.310 + * place itself in the wait set for this object and then to relinquish
7.311 + * any and all synchronization claims on this object. Thread <var>T</var>
7.312 + * becomes disabled for thread scheduling purposes and lies dormant
7.313 + * until one of four things happens:
7.314 + * <ul>
7.315 + * <li>Some other thread invokes the {@code notify} method for this
7.316 + * object and thread <var>T</var> happens to be arbitrarily chosen as
7.317 + * the thread to be awakened.
7.318 + * <li>Some other thread invokes the {@code notifyAll} method for this
7.319 + * object.
7.320 + * <li>Some other thread {@linkplain Thread#interrupt() interrupts}
7.321 + * thread <var>T</var>.
7.322 + * <li>The specified amount of real time has elapsed, more or less. If
7.323 + * {@code timeout} is zero, however, then real time is not taken into
7.324 + * consideration and the thread simply waits until notified.
7.325 + * </ul>
7.326 + * The thread <var>T</var> is then removed from the wait set for this
7.327 + * object and re-enabled for thread scheduling. It then competes in the
7.328 + * usual manner with other threads for the right to synchronize on the
7.329 + * object; once it has gained control of the object, all its
7.330 + * synchronization claims on the object are restored to the status quo
7.331 + * ante - that is, to the situation as of the time that the {@code wait}
7.332 + * method was invoked. Thread <var>T</var> then returns from the
7.333 + * invocation of the {@code wait} method. Thus, on return from the
7.334 + * {@code wait} method, the synchronization state of the object and of
7.335 + * thread {@code T} is exactly as it was when the {@code wait} method
7.336 + * was invoked.
7.337 + * <p>
7.338 + * A thread can also wake up without being notified, interrupted, or
7.339 + * timing out, a so-called <i>spurious wakeup</i>. While this will rarely
7.340 + * occur in practice, applications must guard against it by testing for
7.341 + * the condition that should have caused the thread to be awakened, and
7.342 + * continuing to wait if the condition is not satisfied. In other words,
7.343 + * waits should always occur in loops, like this one:
7.344 + * <pre>
7.345 + * synchronized (obj) {
7.346 + * while (<condition does not hold>)
7.347 + * obj.wait(timeout);
7.348 + * ... // Perform action appropriate to condition
7.349 + * }
7.350 + * </pre>
7.351 + * (For more information on this topic, see Section 3.2.3 in Doug Lea's
7.352 + * "Concurrent Programming in Java (Second Edition)" (Addison-Wesley,
7.353 + * 2000), or Item 50 in Joshua Bloch's "Effective Java Programming
7.354 + * Language Guide" (Addison-Wesley, 2001).
7.355 + *
7.356 + * <p>If the current thread is {@linkplain java.lang.Thread#interrupt()
7.357 + * interrupted} by any thread before or while it is waiting, then an
7.358 + * {@code InterruptedException} is thrown. This exception is not
7.359 + * thrown until the lock status of this object has been restored as
7.360 + * described above.
7.361 + *
7.362 + * <p>
7.363 + * Note that the {@code wait} method, as it places the current thread
7.364 + * into the wait set for this object, unlocks only this object; any
7.365 + * other objects on which the current thread may be synchronized remain
7.366 + * locked while the thread waits.
7.367 + * <p>
7.368 + * This method should only be called by a thread that is the owner
7.369 + * of this object's monitor. See the {@code notify} method for a
7.370 + * description of the ways in which a thread can become the owner of
7.371 + * a monitor.
7.372 + *
7.373 + * @param timeout the maximum time to wait in milliseconds.
7.374 + * @exception IllegalArgumentException if the value of timeout is
7.375 + * negative.
7.376 + * @exception IllegalMonitorStateException if the current thread is not
7.377 + * the owner of the object's monitor.
7.378 + * @exception InterruptedException if any thread interrupted the
7.379 + * current thread before or while the current thread
7.380 + * was waiting for a notification. The <i>interrupted
7.381 + * status</i> of the current thread is cleared when
7.382 + * this exception is thrown.
7.383 + * @see java.lang.Object#notify()
7.384 + * @see java.lang.Object#notifyAll()
7.385 + */
7.386 + public final native void wait(long timeout) throws InterruptedException;
7.387 +
7.388 + /**
7.389 + * Causes the current thread to wait until another thread invokes the
7.390 + * {@link java.lang.Object#notify()} method or the
7.391 + * {@link java.lang.Object#notifyAll()} method for this object, or
7.392 + * some other thread interrupts the current thread, or a certain
7.393 + * amount of real time has elapsed.
7.394 + * <p>
7.395 + * This method is similar to the {@code wait} method of one
7.396 + * argument, but it allows finer control over the amount of time to
7.397 + * wait for a notification before giving up. The amount of real time,
7.398 + * measured in nanoseconds, is given by:
7.399 + * <blockquote>
7.400 + * <pre>
7.401 + * 1000000*timeout+nanos</pre></blockquote>
7.402 + * <p>
7.403 + * In all other respects, this method does the same thing as the
7.404 + * method {@link #wait(long)} of one argument. In particular,
7.405 + * {@code wait(0, 0)} means the same thing as {@code wait(0)}.
7.406 + * <p>
7.407 + * The current thread must own this object's monitor. The thread
7.408 + * releases ownership of this monitor and waits until either of the
7.409 + * following two conditions has occurred:
7.410 + * <ul>
7.411 + * <li>Another thread notifies threads waiting on this object's monitor
7.412 + * to wake up either through a call to the {@code notify} method
7.413 + * or the {@code notifyAll} method.
7.414 + * <li>The timeout period, specified by {@code timeout}
7.415 + * milliseconds plus {@code nanos} nanoseconds arguments, has
7.416 + * elapsed.
7.417 + * </ul>
7.418 + * <p>
7.419 + * The thread then waits until it can re-obtain ownership of the
7.420 + * monitor and resumes execution.
7.421 + * <p>
7.422 + * As in the one argument version, interrupts and spurious wakeups are
7.423 + * possible, and this method should always be used in a loop:
7.424 + * <pre>
7.425 + * synchronized (obj) {
7.426 + * while (<condition does not hold>)
7.427 + * obj.wait(timeout, nanos);
7.428 + * ... // Perform action appropriate to condition
7.429 + * }
7.430 + * </pre>
7.431 + * This method should only be called by a thread that is the owner
7.432 + * of this object's monitor. See the {@code notify} method for a
7.433 + * description of the ways in which a thread can become the owner of
7.434 + * a monitor.
7.435 + *
7.436 + * @param timeout the maximum time to wait in milliseconds.
7.437 + * @param nanos additional time, in nanoseconds range
7.438 + * 0-999999.
7.439 + * @exception IllegalArgumentException if the value of timeout is
7.440 + * negative or the value of nanos is
7.441 + * not in the range 0-999999.
7.442 + * @exception IllegalMonitorStateException if the current thread is not
7.443 + * the owner of this object's monitor.
7.444 + * @exception InterruptedException if any thread interrupted the
7.445 + * current thread before or while the current thread
7.446 + * was waiting for a notification. The <i>interrupted
7.447 + * status</i> of the current thread is cleared when
7.448 + * this exception is thrown.
7.449 + */
7.450 + public final void wait(long timeout, int nanos) throws InterruptedException {
7.451 + if (timeout < 0) {
7.452 + throw new IllegalArgumentException("timeout value is negative");
7.453 + }
7.454 +
7.455 + if (nanos < 0 || nanos > 999999) {
7.456 + throw new IllegalArgumentException(
7.457 + "nanosecond timeout value out of range");
7.458 + }
7.459 +
7.460 + if (nanos >= 500000 || (nanos != 0 && timeout == 0)) {
7.461 + timeout++;
7.462 + }
7.463 +
7.464 + wait(timeout);
7.465 + }
7.466 +
7.467 + /**
7.468 + * Causes the current thread to wait until another thread invokes the
7.469 + * {@link java.lang.Object#notify()} method or the
7.470 + * {@link java.lang.Object#notifyAll()} method for this object.
7.471 + * In other words, this method behaves exactly as if it simply
7.472 + * performs the call {@code wait(0)}.
7.473 + * <p>
7.474 + * The current thread must own this object's monitor. The thread
7.475 + * releases ownership of this monitor and waits until another thread
7.476 + * notifies threads waiting on this object's monitor to wake up
7.477 + * either through a call to the {@code notify} method or the
7.478 + * {@code notifyAll} method. The thread then waits until it can
7.479 + * re-obtain ownership of the monitor and resumes execution.
7.480 + * <p>
7.481 + * As in the one argument version, interrupts and spurious wakeups are
7.482 + * possible, and this method should always be used in a loop:
7.483 + * <pre>
7.484 + * synchronized (obj) {
7.485 + * while (<condition does not hold>)
7.486 + * obj.wait();
7.487 + * ... // Perform action appropriate to condition
7.488 + * }
7.489 + * </pre>
7.490 + * This method should only be called by a thread that is the owner
7.491 + * of this object's monitor. See the {@code notify} method for a
7.492 + * description of the ways in which a thread can become the owner of
7.493 + * a monitor.
7.494 + *
7.495 + * @exception IllegalMonitorStateException if the current thread is not
7.496 + * the owner of the object's monitor.
7.497 + * @exception InterruptedException if any thread interrupted the
7.498 + * current thread before or while the current thread
7.499 + * was waiting for a notification. The <i>interrupted
7.500 + * status</i> of the current thread is cleared when
7.501 + * this exception is thrown.
7.502 + * @see java.lang.Object#notify()
7.503 + * @see java.lang.Object#notifyAll()
7.504 + */
7.505 + public final void wait() throws InterruptedException {
7.506 + wait(0);
7.507 + }
7.508 +
7.509 + /**
7.510 + * Called by the garbage collector on an object when garbage collection
7.511 + * determines that there are no more references to the object.
7.512 + * A subclass overrides the {@code finalize} method to dispose of
7.513 + * system resources or to perform other cleanup.
7.514 + * <p>
7.515 + * The general contract of {@code finalize} is that it is invoked
7.516 + * if and when the Java<font size="-2"><sup>TM</sup></font> virtual
7.517 + * machine has determined that there is no longer any
7.518 + * means by which this object can be accessed by any thread that has
7.519 + * not yet died, except as a result of an action taken by the
7.520 + * finalization of some other object or class which is ready to be
7.521 + * finalized. The {@code finalize} method may take any action, including
7.522 + * making this object available again to other threads; the usual purpose
7.523 + * of {@code finalize}, however, is to perform cleanup actions before
7.524 + * the object is irrevocably discarded. For example, the finalize method
7.525 + * for an object that represents an input/output connection might perform
7.526 + * explicit I/O transactions to break the connection before the object is
7.527 + * permanently discarded.
7.528 + * <p>
7.529 + * The {@code finalize} method of class {@code Object} performs no
7.530 + * special action; it simply returns normally. Subclasses of
7.531 + * {@code Object} may override this definition.
7.532 + * <p>
7.533 + * The Java programming language does not guarantee which thread will
7.534 + * invoke the {@code finalize} method for any given object. It is
7.535 + * guaranteed, however, that the thread that invokes finalize will not
7.536 + * be holding any user-visible synchronization locks when finalize is
7.537 + * invoked. If an uncaught exception is thrown by the finalize method,
7.538 + * the exception is ignored and finalization of that object terminates.
7.539 + * <p>
7.540 + * After the {@code finalize} method has been invoked for an object, no
7.541 + * further action is taken until the Java virtual machine has again
7.542 + * determined that there is no longer any means by which this object can
7.543 + * be accessed by any thread that has not yet died, including possible
7.544 + * actions by other objects or classes which are ready to be finalized,
7.545 + * at which point the object may be discarded.
7.546 + * <p>
7.547 + * The {@code finalize} method is never invoked more than once by a Java
7.548 + * virtual machine for any given object.
7.549 + * <p>
7.550 + * Any exception thrown by the {@code finalize} method causes
7.551 + * the finalization of this object to be halted, but is otherwise
7.552 + * ignored.
7.553 + *
7.554 + * @throws Throwable the {@code Exception} raised by this method
7.555 + */
7.556 + protected void finalize() throws Throwable { }
7.557 +}
8.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
8.2 +++ b/emul/src/main/java/java/lang/String.java Fri Sep 28 17:59:03 2012 +0200
8.3 @@ -0,0 +1,3077 @@
8.4 +/*
8.5 + * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
8.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
8.7 + *
8.8 + * This code is free software; you can redistribute it and/or modify it
8.9 + * under the terms of the GNU General Public License version 2 only, as
8.10 + * published by the Free Software Foundation. Oracle designates this
8.11 + * particular file as subject to the "Classpath" exception as provided
8.12 + * by Oracle in the LICENSE file that accompanied this code.
8.13 + *
8.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
8.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
8.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
8.17 + * version 2 for more details (a copy is included in the LICENSE file that
8.18 + * accompanied this code).
8.19 + *
8.20 + * You should have received a copy of the GNU General Public License version
8.21 + * 2 along with this work; if not, write to the Free Software Foundation,
8.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
8.23 + *
8.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
8.25 + * or visit www.oracle.com if you need additional information or have any
8.26 + * questions.
8.27 + */
8.28 +
8.29 +package java.lang;
8.30 +
8.31 +import java.io.ObjectStreamClass;
8.32 +import java.io.ObjectStreamField;
8.33 +import java.io.UnsupportedEncodingException;
8.34 +import java.nio.charset.Charset;
8.35 +import java.util.ArrayList;
8.36 +import java.util.Arrays;
8.37 +import java.util.Comparator;
8.38 +import java.util.Formatter;
8.39 +import java.util.Locale;
8.40 +import java.util.regex.Matcher;
8.41 +import java.util.regex.Pattern;
8.42 +import java.util.regex.PatternSyntaxException;
8.43 +
8.44 +/**
8.45 + * The <code>String</code> class represents character strings. All
8.46 + * string literals in Java programs, such as <code>"abc"</code>, are
8.47 + * implemented as instances of this class.
8.48 + * <p>
8.49 + * Strings are constant; their values cannot be changed after they
8.50 + * are created. String buffers support mutable strings.
8.51 + * Because String objects are immutable they can be shared. For example:
8.52 + * <p><blockquote><pre>
8.53 + * String str = "abc";
8.54 + * </pre></blockquote><p>
8.55 + * is equivalent to:
8.56 + * <p><blockquote><pre>
8.57 + * char data[] = {'a', 'b', 'c'};
8.58 + * String str = new String(data);
8.59 + * </pre></blockquote><p>
8.60 + * Here are some more examples of how strings can be used:
8.61 + * <p><blockquote><pre>
8.62 + * System.out.println("abc");
8.63 + * String cde = "cde";
8.64 + * System.out.println("abc" + cde);
8.65 + * String c = "abc".substring(2,3);
8.66 + * String d = cde.substring(1, 2);
8.67 + * </pre></blockquote>
8.68 + * <p>
8.69 + * The class <code>String</code> includes methods for examining
8.70 + * individual characters of the sequence, for comparing strings, for
8.71 + * searching strings, for extracting substrings, and for creating a
8.72 + * copy of a string with all characters translated to uppercase or to
8.73 + * lowercase. Case mapping is based on the Unicode Standard version
8.74 + * specified by the {@link java.lang.Character Character} class.
8.75 + * <p>
8.76 + * The Java language provides special support for the string
8.77 + * concatenation operator ( + ), and for conversion of
8.78 + * other objects to strings. String concatenation is implemented
8.79 + * through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
8.80 + * class and its <code>append</code> method.
8.81 + * String conversions are implemented through the method
8.82 + * <code>toString</code>, defined by <code>Object</code> and
8.83 + * inherited by all classes in Java. For additional information on
8.84 + * string concatenation and conversion, see Gosling, Joy, and Steele,
8.85 + * <i>The Java Language Specification</i>.
8.86 + *
8.87 + * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
8.88 + * or method in this class will cause a {@link NullPointerException} to be
8.89 + * thrown.
8.90 + *
8.91 + * <p>A <code>String</code> represents a string in the UTF-16 format
8.92 + * in which <em>supplementary characters</em> are represented by <em>surrogate
8.93 + * pairs</em> (see the section <a href="Character.html#unicode">Unicode
8.94 + * Character Representations</a> in the <code>Character</code> class for
8.95 + * more information).
8.96 + * Index values refer to <code>char</code> code units, so a supplementary
8.97 + * character uses two positions in a <code>String</code>.
8.98 + * <p>The <code>String</code> class provides methods for dealing with
8.99 + * Unicode code points (i.e., characters), in addition to those for
8.100 + * dealing with Unicode code units (i.e., <code>char</code> values).
8.101 + *
8.102 + * @author Lee Boynton
8.103 + * @author Arthur van Hoff
8.104 + * @author Martin Buchholz
8.105 + * @author Ulf Zibis
8.106 + * @see java.lang.Object#toString()
8.107 + * @see java.lang.StringBuffer
8.108 + * @see java.lang.StringBuilder
8.109 + * @see java.nio.charset.Charset
8.110 + * @since JDK1.0
8.111 + */
8.112 +
8.113 +public final class String
8.114 + implements java.io.Serializable, Comparable<String>, CharSequence
8.115 +{
8.116 + /** The value is used for character storage. */
8.117 + private final char value[];
8.118 +
8.119 + /** The offset is the first index of the storage that is used. */
8.120 + private final int offset;
8.121 +
8.122 + /** The count is the number of characters in the String. */
8.123 + private final int count;
8.124 +
8.125 + /** Cache the hash code for the string */
8.126 + private int hash; // Default to 0
8.127 +
8.128 + /** use serialVersionUID from JDK 1.0.2 for interoperability */
8.129 + private static final long serialVersionUID = -6849794470754667710L;
8.130 +
8.131 + /**
8.132 + * Class String is special cased within the Serialization Stream Protocol.
8.133 + *
8.134 + * A String instance is written initially into an ObjectOutputStream in the
8.135 + * following format:
8.136 + * <pre>
8.137 + * <code>TC_STRING</code> (utf String)
8.138 + * </pre>
8.139 + * The String is written by method <code>DataOutput.writeUTF</code>.
8.140 + * A new handle is generated to refer to all future references to the
8.141 + * string instance within the stream.
8.142 + */
8.143 + private static final ObjectStreamField[] serialPersistentFields =
8.144 + new ObjectStreamField[0];
8.145 +
8.146 + /**
8.147 + * Initializes a newly created {@code String} object so that it represents
8.148 + * an empty character sequence. Note that use of this constructor is
8.149 + * unnecessary since Strings are immutable.
8.150 + */
8.151 + public String() {
8.152 + this.offset = 0;
8.153 + this.count = 0;
8.154 + this.value = new char[0];
8.155 + }
8.156 +
8.157 + /**
8.158 + * Initializes a newly created {@code String} object so that it represents
8.159 + * the same sequence of characters as the argument; in other words, the
8.160 + * newly created string is a copy of the argument string. Unless an
8.161 + * explicit copy of {@code original} is needed, use of this constructor is
8.162 + * unnecessary since Strings are immutable.
8.163 + *
8.164 + * @param original
8.165 + * A {@code String}
8.166 + */
8.167 + public String(String original) {
8.168 + int size = original.count;
8.169 + char[] originalValue = original.value;
8.170 + char[] v;
8.171 + if (originalValue.length > size) {
8.172 + // The array representing the String is bigger than the new
8.173 + // String itself. Perhaps this constructor is being called
8.174 + // in order to trim the baggage, so make a copy of the array.
8.175 + int off = original.offset;
8.176 + v = Arrays.copyOfRange(originalValue, off, off+size);
8.177 + } else {
8.178 + // The array representing the String is the same
8.179 + // size as the String, so no point in making a copy.
8.180 + v = originalValue;
8.181 + }
8.182 + this.offset = 0;
8.183 + this.count = size;
8.184 + this.value = v;
8.185 + }
8.186 +
8.187 + /**
8.188 + * Allocates a new {@code String} so that it represents the sequence of
8.189 + * characters currently contained in the character array argument. The
8.190 + * contents of the character array are copied; subsequent modification of
8.191 + * the character array does not affect the newly created string.
8.192 + *
8.193 + * @param value
8.194 + * The initial value of the string
8.195 + */
8.196 + public String(char value[]) {
8.197 + int size = value.length;
8.198 + this.offset = 0;
8.199 + this.count = size;
8.200 + this.value = Arrays.copyOf(value, size);
8.201 + }
8.202 +
8.203 + /**
8.204 + * Allocates a new {@code String} that contains characters from a subarray
8.205 + * of the character array argument. The {@code offset} argument is the
8.206 + * index of the first character of the subarray and the {@code count}
8.207 + * argument specifies the length of the subarray. The contents of the
8.208 + * subarray are copied; subsequent modification of the character array does
8.209 + * not affect the newly created string.
8.210 + *
8.211 + * @param value
8.212 + * Array that is the source of characters
8.213 + *
8.214 + * @param offset
8.215 + * The initial offset
8.216 + *
8.217 + * @param count
8.218 + * The length
8.219 + *
8.220 + * @throws IndexOutOfBoundsException
8.221 + * If the {@code offset} and {@code count} arguments index
8.222 + * characters outside the bounds of the {@code value} array
8.223 + */
8.224 + public String(char value[], int offset, int count) {
8.225 + if (offset < 0) {
8.226 + throw new StringIndexOutOfBoundsException(offset);
8.227 + }
8.228 + if (count < 0) {
8.229 + throw new StringIndexOutOfBoundsException(count);
8.230 + }
8.231 + // Note: offset or count might be near -1>>>1.
8.232 + if (offset > value.length - count) {
8.233 + throw new StringIndexOutOfBoundsException(offset + count);
8.234 + }
8.235 + this.offset = 0;
8.236 + this.count = count;
8.237 + this.value = Arrays.copyOfRange(value, offset, offset+count);
8.238 + }
8.239 +
8.240 + /**
8.241 + * Allocates a new {@code String} that contains characters from a subarray
8.242 + * of the <a href="Character.html#unicode">Unicode code point</a> array
8.243 + * argument. The {@code offset} argument is the index of the first code
8.244 + * point of the subarray and the {@code count} argument specifies the
8.245 + * length of the subarray. The contents of the subarray are converted to
8.246 + * {@code char}s; subsequent modification of the {@code int} array does not
8.247 + * affect the newly created string.
8.248 + *
8.249 + * @param codePoints
8.250 + * Array that is the source of Unicode code points
8.251 + *
8.252 + * @param offset
8.253 + * The initial offset
8.254 + *
8.255 + * @param count
8.256 + * The length
8.257 + *
8.258 + * @throws IllegalArgumentException
8.259 + * If any invalid Unicode code point is found in {@code
8.260 + * codePoints}
8.261 + *
8.262 + * @throws IndexOutOfBoundsException
8.263 + * If the {@code offset} and {@code count} arguments index
8.264 + * characters outside the bounds of the {@code codePoints} array
8.265 + *
8.266 + * @since 1.5
8.267 + */
8.268 + public String(int[] codePoints, int offset, int count) {
8.269 + if (offset < 0) {
8.270 + throw new StringIndexOutOfBoundsException(offset);
8.271 + }
8.272 + if (count < 0) {
8.273 + throw new StringIndexOutOfBoundsException(count);
8.274 + }
8.275 + // Note: offset or count might be near -1>>>1.
8.276 + if (offset > codePoints.length - count) {
8.277 + throw new StringIndexOutOfBoundsException(offset + count);
8.278 + }
8.279 +
8.280 + final int end = offset + count;
8.281 +
8.282 + // Pass 1: Compute precise size of char[]
8.283 + int n = count;
8.284 + for (int i = offset; i < end; i++) {
8.285 + int c = codePoints[i];
8.286 + if (Character.isBmpCodePoint(c))
8.287 + continue;
8.288 + else if (Character.isValidCodePoint(c))
8.289 + n++;
8.290 + else throw new IllegalArgumentException(Integer.toString(c));
8.291 + }
8.292 +
8.293 + // Pass 2: Allocate and fill in char[]
8.294 + final char[] v = new char[n];
8.295 +
8.296 + for (int i = offset, j = 0; i < end; i++, j++) {
8.297 + int c = codePoints[i];
8.298 + if (Character.isBmpCodePoint(c))
8.299 + v[j] = (char) c;
8.300 + else
8.301 + Character.toSurrogates(c, v, j++);
8.302 + }
8.303 +
8.304 + this.value = v;
8.305 + this.count = n;
8.306 + this.offset = 0;
8.307 + }
8.308 +
8.309 + /**
8.310 + * Allocates a new {@code String} constructed from a subarray of an array
8.311 + * of 8-bit integer values.
8.312 + *
8.313 + * <p> The {@code offset} argument is the index of the first byte of the
8.314 + * subarray, and the {@code count} argument specifies the length of the
8.315 + * subarray.
8.316 + *
8.317 + * <p> Each {@code byte} in the subarray is converted to a {@code char} as
8.318 + * specified in the method above.
8.319 + *
8.320 + * @deprecated This method does not properly convert bytes into characters.
8.321 + * As of JDK 1.1, the preferred way to do this is via the
8.322 + * {@code String} constructors that take a {@link
8.323 + * java.nio.charset.Charset}, charset name, or that use the platform's
8.324 + * default charset.
8.325 + *
8.326 + * @param ascii
8.327 + * The bytes to be converted to characters
8.328 + *
8.329 + * @param hibyte
8.330 + * The top 8 bits of each 16-bit Unicode code unit
8.331 + *
8.332 + * @param offset
8.333 + * The initial offset
8.334 + * @param count
8.335 + * The length
8.336 + *
8.337 + * @throws IndexOutOfBoundsException
8.338 + * If the {@code offset} or {@code count} argument is invalid
8.339 + *
8.340 + * @see #String(byte[], int)
8.341 + * @see #String(byte[], int, int, java.lang.String)
8.342 + * @see #String(byte[], int, int, java.nio.charset.Charset)
8.343 + * @see #String(byte[], int, int)
8.344 + * @see #String(byte[], java.lang.String)
8.345 + * @see #String(byte[], java.nio.charset.Charset)
8.346 + * @see #String(byte[])
8.347 + */
8.348 + @Deprecated
8.349 + public String(byte ascii[], int hibyte, int offset, int count) {
8.350 + checkBounds(ascii, offset, count);
8.351 + char value[] = new char[count];
8.352 +
8.353 + if (hibyte == 0) {
8.354 + for (int i = count ; i-- > 0 ;) {
8.355 + value[i] = (char) (ascii[i + offset] & 0xff);
8.356 + }
8.357 + } else {
8.358 + hibyte <<= 8;
8.359 + for (int i = count ; i-- > 0 ;) {
8.360 + value[i] = (char) (hibyte | (ascii[i + offset] & 0xff));
8.361 + }
8.362 + }
8.363 + this.offset = 0;
8.364 + this.count = count;
8.365 + this.value = value;
8.366 + }
8.367 +
8.368 + /**
8.369 + * Allocates a new {@code String} containing characters constructed from
8.370 + * an array of 8-bit integer values. Each character <i>c</i>in the
8.371 + * resulting string is constructed from the corresponding component
8.372 + * <i>b</i> in the byte array such that:
8.373 + *
8.374 + * <blockquote><pre>
8.375 + * <b><i>c</i></b> == (char)(((hibyte & 0xff) << 8)
8.376 + * | (<b><i>b</i></b> & 0xff))
8.377 + * </pre></blockquote>
8.378 + *
8.379 + * @deprecated This method does not properly convert bytes into
8.380 + * characters. As of JDK 1.1, the preferred way to do this is via the
8.381 + * {@code String} constructors that take a {@link
8.382 + * java.nio.charset.Charset}, charset name, or that use the platform's
8.383 + * default charset.
8.384 + *
8.385 + * @param ascii
8.386 + * The bytes to be converted to characters
8.387 + *
8.388 + * @param hibyte
8.389 + * The top 8 bits of each 16-bit Unicode code unit
8.390 + *
8.391 + * @see #String(byte[], int, int, java.lang.String)
8.392 + * @see #String(byte[], int, int, java.nio.charset.Charset)
8.393 + * @see #String(byte[], int, int)
8.394 + * @see #String(byte[], java.lang.String)
8.395 + * @see #String(byte[], java.nio.charset.Charset)
8.396 + * @see #String(byte[])
8.397 + */
8.398 + @Deprecated
8.399 + public String(byte ascii[], int hibyte) {
8.400 + this(ascii, hibyte, 0, ascii.length);
8.401 + }
8.402 +
8.403 + /* Common private utility method used to bounds check the byte array
8.404 + * and requested offset & length values used by the String(byte[],..)
8.405 + * constructors.
8.406 + */
8.407 + private static void checkBounds(byte[] bytes, int offset, int length) {
8.408 + if (length < 0)
8.409 + throw new StringIndexOutOfBoundsException(length);
8.410 + if (offset < 0)
8.411 + throw new StringIndexOutOfBoundsException(offset);
8.412 + if (offset > bytes.length - length)
8.413 + throw new StringIndexOutOfBoundsException(offset + length);
8.414 + }
8.415 +
8.416 + /**
8.417 + * Constructs a new {@code String} by decoding the specified subarray of
8.418 + * bytes using the specified charset. The length of the new {@code String}
8.419 + * is a function of the charset, and hence may not be equal to the length
8.420 + * of the subarray.
8.421 + *
8.422 + * <p> The behavior of this constructor when the given bytes are not valid
8.423 + * in the given charset is unspecified. The {@link
8.424 + * java.nio.charset.CharsetDecoder} class should be used when more control
8.425 + * over the decoding process is required.
8.426 + *
8.427 + * @param bytes
8.428 + * The bytes to be decoded into characters
8.429 + *
8.430 + * @param offset
8.431 + * The index of the first byte to decode
8.432 + *
8.433 + * @param length
8.434 + * The number of bytes to decode
8.435 +
8.436 + * @param charsetName
8.437 + * The name of a supported {@linkplain java.nio.charset.Charset
8.438 + * charset}
8.439 + *
8.440 + * @throws UnsupportedEncodingException
8.441 + * If the named charset is not supported
8.442 + *
8.443 + * @throws IndexOutOfBoundsException
8.444 + * If the {@code offset} and {@code length} arguments index
8.445 + * characters outside the bounds of the {@code bytes} array
8.446 + *
8.447 + * @since JDK1.1
8.448 + */
8.449 + public String(byte bytes[], int offset, int length, String charsetName)
8.450 + throws UnsupportedEncodingException
8.451 + {
8.452 + if (charsetName == null)
8.453 + throw new NullPointerException("charsetName");
8.454 + checkBounds(bytes, offset, length);
8.455 + char[] v = StringCoding.decode(charsetName, bytes, offset, length);
8.456 + this.offset = 0;
8.457 + this.count = v.length;
8.458 + this.value = v;
8.459 + }
8.460 +
8.461 + /**
8.462 + * Constructs a new {@code String} by decoding the specified subarray of
8.463 + * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
8.464 + * The length of the new {@code String} is a function of the charset, and
8.465 + * hence may not be equal to the length of the subarray.
8.466 + *
8.467 + * <p> This method always replaces malformed-input and unmappable-character
8.468 + * sequences with this charset's default replacement string. The {@link
8.469 + * java.nio.charset.CharsetDecoder} class should be used when more control
8.470 + * over the decoding process is required.
8.471 + *
8.472 + * @param bytes
8.473 + * The bytes to be decoded into characters
8.474 + *
8.475 + * @param offset
8.476 + * The index of the first byte to decode
8.477 + *
8.478 + * @param length
8.479 + * The number of bytes to decode
8.480 + *
8.481 + * @param charset
8.482 + * The {@linkplain java.nio.charset.Charset charset} to be used to
8.483 + * decode the {@code bytes}
8.484 + *
8.485 + * @throws IndexOutOfBoundsException
8.486 + * If the {@code offset} and {@code length} arguments index
8.487 + * characters outside the bounds of the {@code bytes} array
8.488 + *
8.489 + * @since 1.6
8.490 + */
8.491 + public String(byte bytes[], int offset, int length, Charset charset) {
8.492 + if (charset == null)
8.493 + throw new NullPointerException("charset");
8.494 + checkBounds(bytes, offset, length);
8.495 + char[] v = StringCoding.decode(charset, bytes, offset, length);
8.496 + this.offset = 0;
8.497 + this.count = v.length;
8.498 + this.value = v;
8.499 + }
8.500 +
8.501 + /**
8.502 + * Constructs a new {@code String} by decoding the specified array of bytes
8.503 + * using the specified {@linkplain java.nio.charset.Charset charset}. The
8.504 + * length of the new {@code String} is a function of the charset, and hence
8.505 + * may not be equal to the length of the byte array.
8.506 + *
8.507 + * <p> The behavior of this constructor when the given bytes are not valid
8.508 + * in the given charset is unspecified. The {@link
8.509 + * java.nio.charset.CharsetDecoder} class should be used when more control
8.510 + * over the decoding process is required.
8.511 + *
8.512 + * @param bytes
8.513 + * The bytes to be decoded into characters
8.514 + *
8.515 + * @param charsetName
8.516 + * The name of a supported {@linkplain java.nio.charset.Charset
8.517 + * charset}
8.518 + *
8.519 + * @throws UnsupportedEncodingException
8.520 + * If the named charset is not supported
8.521 + *
8.522 + * @since JDK1.1
8.523 + */
8.524 + public String(byte bytes[], String charsetName)
8.525 + throws UnsupportedEncodingException
8.526 + {
8.527 + this(bytes, 0, bytes.length, charsetName);
8.528 + }
8.529 +
8.530 + /**
8.531 + * Constructs a new {@code String} by decoding the specified array of
8.532 + * bytes using the specified {@linkplain java.nio.charset.Charset charset}.
8.533 + * The length of the new {@code String} is a function of the charset, and
8.534 + * hence may not be equal to the length of the byte array.
8.535 + *
8.536 + * <p> This method always replaces malformed-input and unmappable-character
8.537 + * sequences with this charset's default replacement string. The {@link
8.538 + * java.nio.charset.CharsetDecoder} class should be used when more control
8.539 + * over the decoding process is required.
8.540 + *
8.541 + * @param bytes
8.542 + * The bytes to be decoded into characters
8.543 + *
8.544 + * @param charset
8.545 + * The {@linkplain java.nio.charset.Charset charset} to be used to
8.546 + * decode the {@code bytes}
8.547 + *
8.548 + * @since 1.6
8.549 + */
8.550 + public String(byte bytes[], Charset charset) {
8.551 + this(bytes, 0, bytes.length, charset);
8.552 + }
8.553 +
8.554 + /**
8.555 + * Constructs a new {@code String} by decoding the specified subarray of
8.556 + * bytes using the platform's default charset. The length of the new
8.557 + * {@code String} is a function of the charset, and hence may not be equal
8.558 + * to the length of the subarray.
8.559 + *
8.560 + * <p> The behavior of this constructor when the given bytes are not valid
8.561 + * in the default charset is unspecified. The {@link
8.562 + * java.nio.charset.CharsetDecoder} class should be used when more control
8.563 + * over the decoding process is required.
8.564 + *
8.565 + * @param bytes
8.566 + * The bytes to be decoded into characters
8.567 + *
8.568 + * @param offset
8.569 + * The index of the first byte to decode
8.570 + *
8.571 + * @param length
8.572 + * The number of bytes to decode
8.573 + *
8.574 + * @throws IndexOutOfBoundsException
8.575 + * If the {@code offset} and the {@code length} arguments index
8.576 + * characters outside the bounds of the {@code bytes} array
8.577 + *
8.578 + * @since JDK1.1
8.579 + */
8.580 + public String(byte bytes[], int offset, int length) {
8.581 + checkBounds(bytes, offset, length);
8.582 + char[] v = StringCoding.decode(bytes, offset, length);
8.583 + this.offset = 0;
8.584 + this.count = v.length;
8.585 + this.value = v;
8.586 + }
8.587 +
8.588 + /**
8.589 + * Constructs a new {@code String} by decoding the specified array of bytes
8.590 + * using the platform's default charset. The length of the new {@code
8.591 + * String} is a function of the charset, and hence may not be equal to the
8.592 + * length of the byte array.
8.593 + *
8.594 + * <p> The behavior of this constructor when the given bytes are not valid
8.595 + * in the default charset is unspecified. The {@link
8.596 + * java.nio.charset.CharsetDecoder} class should be used when more control
8.597 + * over the decoding process is required.
8.598 + *
8.599 + * @param bytes
8.600 + * The bytes to be decoded into characters
8.601 + *
8.602 + * @since JDK1.1
8.603 + */
8.604 + public String(byte bytes[]) {
8.605 + this(bytes, 0, bytes.length);
8.606 + }
8.607 +
8.608 + /**
8.609 + * Allocates a new string that contains the sequence of characters
8.610 + * currently contained in the string buffer argument. The contents of the
8.611 + * string buffer are copied; subsequent modification of the string buffer
8.612 + * does not affect the newly created string.
8.613 + *
8.614 + * @param buffer
8.615 + * A {@code StringBuffer}
8.616 + */
8.617 + public String(StringBuffer buffer) {
8.618 + String result = buffer.toString();
8.619 + this.value = result.value;
8.620 + this.count = result.count;
8.621 + this.offset = result.offset;
8.622 + }
8.623 +
8.624 + /**
8.625 + * Allocates a new string that contains the sequence of characters
8.626 + * currently contained in the string builder argument. The contents of the
8.627 + * string builder are copied; subsequent modification of the string builder
8.628 + * does not affect the newly created string.
8.629 + *
8.630 + * <p> This constructor is provided to ease migration to {@code
8.631 + * StringBuilder}. Obtaining a string from a string builder via the {@code
8.632 + * toString} method is likely to run faster and is generally preferred.
8.633 + *
8.634 + * @param builder
8.635 + * A {@code StringBuilder}
8.636 + *
8.637 + * @since 1.5
8.638 + */
8.639 + public String(StringBuilder builder) {
8.640 + String result = builder.toString();
8.641 + this.value = result.value;
8.642 + this.count = result.count;
8.643 + this.offset = result.offset;
8.644 + }
8.645 +
8.646 +
8.647 + // Package private constructor which shares value array for speed.
8.648 + String(int offset, int count, char value[]) {
8.649 + this.value = value;
8.650 + this.offset = offset;
8.651 + this.count = count;
8.652 + }
8.653 +
8.654 + /**
8.655 + * Returns the length of this string.
8.656 + * The length is equal to the number of <a href="Character.html#unicode">Unicode
8.657 + * code units</a> in the string.
8.658 + *
8.659 + * @return the length of the sequence of characters represented by this
8.660 + * object.
8.661 + */
8.662 + public int length() {
8.663 + return count;
8.664 + }
8.665 +
8.666 + /**
8.667 + * Returns <tt>true</tt> if, and only if, {@link #length()} is <tt>0</tt>.
8.668 + *
8.669 + * @return <tt>true</tt> if {@link #length()} is <tt>0</tt>, otherwise
8.670 + * <tt>false</tt>
8.671 + *
8.672 + * @since 1.6
8.673 + */
8.674 + public boolean isEmpty() {
8.675 + return count == 0;
8.676 + }
8.677 +
8.678 + /**
8.679 + * Returns the <code>char</code> value at the
8.680 + * specified index. An index ranges from <code>0</code> to
8.681 + * <code>length() - 1</code>. The first <code>char</code> value of the sequence
8.682 + * is at index <code>0</code>, the next at index <code>1</code>,
8.683 + * and so on, as for array indexing.
8.684 + *
8.685 + * <p>If the <code>char</code> value specified by the index is a
8.686 + * <a href="Character.html#unicode">surrogate</a>, the surrogate
8.687 + * value is returned.
8.688 + *
8.689 + * @param index the index of the <code>char</code> value.
8.690 + * @return the <code>char</code> value at the specified index of this string.
8.691 + * The first <code>char</code> value is at index <code>0</code>.
8.692 + * @exception IndexOutOfBoundsException if the <code>index</code>
8.693 + * argument is negative or not less than the length of this
8.694 + * string.
8.695 + */
8.696 + public char charAt(int index) {
8.697 + if ((index < 0) || (index >= count)) {
8.698 + throw new StringIndexOutOfBoundsException(index);
8.699 + }
8.700 + return value[index + offset];
8.701 + }
8.702 +
8.703 + /**
8.704 + * Returns the character (Unicode code point) at the specified
8.705 + * index. The index refers to <code>char</code> values
8.706 + * (Unicode code units) and ranges from <code>0</code> to
8.707 + * {@link #length()}<code> - 1</code>.
8.708 + *
8.709 + * <p> If the <code>char</code> value specified at the given index
8.710 + * is in the high-surrogate range, the following index is less
8.711 + * than the length of this <code>String</code>, and the
8.712 + * <code>char</code> value at the following index is in the
8.713 + * low-surrogate range, then the supplementary code point
8.714 + * corresponding to this surrogate pair is returned. Otherwise,
8.715 + * the <code>char</code> value at the given index is returned.
8.716 + *
8.717 + * @param index the index to the <code>char</code> values
8.718 + * @return the code point value of the character at the
8.719 + * <code>index</code>
8.720 + * @exception IndexOutOfBoundsException if the <code>index</code>
8.721 + * argument is negative or not less than the length of this
8.722 + * string.
8.723 + * @since 1.5
8.724 + */
8.725 + public int codePointAt(int index) {
8.726 + if ((index < 0) || (index >= count)) {
8.727 + throw new StringIndexOutOfBoundsException(index);
8.728 + }
8.729 + return Character.codePointAtImpl(value, offset + index, offset + count);
8.730 + }
8.731 +
8.732 + /**
8.733 + * Returns the character (Unicode code point) before the specified
8.734 + * index. The index refers to <code>char</code> values
8.735 + * (Unicode code units) and ranges from <code>1</code> to {@link
8.736 + * CharSequence#length() length}.
8.737 + *
8.738 + * <p> If the <code>char</code> value at <code>(index - 1)</code>
8.739 + * is in the low-surrogate range, <code>(index - 2)</code> is not
8.740 + * negative, and the <code>char</code> value at <code>(index -
8.741 + * 2)</code> is in the high-surrogate range, then the
8.742 + * supplementary code point value of the surrogate pair is
8.743 + * returned. If the <code>char</code> value at <code>index -
8.744 + * 1</code> is an unpaired low-surrogate or a high-surrogate, the
8.745 + * surrogate value is returned.
8.746 + *
8.747 + * @param index the index following the code point that should be returned
8.748 + * @return the Unicode code point value before the given index.
8.749 + * @exception IndexOutOfBoundsException if the <code>index</code>
8.750 + * argument is less than 1 or greater than the length
8.751 + * of this string.
8.752 + * @since 1.5
8.753 + */
8.754 + public int codePointBefore(int index) {
8.755 + int i = index - 1;
8.756 + if ((i < 0) || (i >= count)) {
8.757 + throw new StringIndexOutOfBoundsException(index);
8.758 + }
8.759 + return Character.codePointBeforeImpl(value, offset + index, offset);
8.760 + }
8.761 +
8.762 + /**
8.763 + * Returns the number of Unicode code points in the specified text
8.764 + * range of this <code>String</code>. The text range begins at the
8.765 + * specified <code>beginIndex</code> and extends to the
8.766 + * <code>char</code> at index <code>endIndex - 1</code>. Thus the
8.767 + * length (in <code>char</code>s) of the text range is
8.768 + * <code>endIndex-beginIndex</code>. Unpaired surrogates within
8.769 + * the text range count as one code point each.
8.770 + *
8.771 + * @param beginIndex the index to the first <code>char</code> of
8.772 + * the text range.
8.773 + * @param endIndex the index after the last <code>char</code> of
8.774 + * the text range.
8.775 + * @return the number of Unicode code points in the specified text
8.776 + * range
8.777 + * @exception IndexOutOfBoundsException if the
8.778 + * <code>beginIndex</code> is negative, or <code>endIndex</code>
8.779 + * is larger than the length of this <code>String</code>, or
8.780 + * <code>beginIndex</code> is larger than <code>endIndex</code>.
8.781 + * @since 1.5
8.782 + */
8.783 + public int codePointCount(int beginIndex, int endIndex) {
8.784 + if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
8.785 + throw new IndexOutOfBoundsException();
8.786 + }
8.787 + return Character.codePointCountImpl(value, offset+beginIndex, endIndex-beginIndex);
8.788 + }
8.789 +
8.790 + /**
8.791 + * Returns the index within this <code>String</code> that is
8.792 + * offset from the given <code>index</code> by
8.793 + * <code>codePointOffset</code> code points. Unpaired surrogates
8.794 + * within the text range given by <code>index</code> and
8.795 + * <code>codePointOffset</code> count as one code point each.
8.796 + *
8.797 + * @param index the index to be offset
8.798 + * @param codePointOffset the offset in code points
8.799 + * @return the index within this <code>String</code>
8.800 + * @exception IndexOutOfBoundsException if <code>index</code>
8.801 + * is negative or larger then the length of this
8.802 + * <code>String</code>, or if <code>codePointOffset</code> is positive
8.803 + * and the substring starting with <code>index</code> has fewer
8.804 + * than <code>codePointOffset</code> code points,
8.805 + * or if <code>codePointOffset</code> is negative and the substring
8.806 + * before <code>index</code> has fewer than the absolute value
8.807 + * of <code>codePointOffset</code> code points.
8.808 + * @since 1.5
8.809 + */
8.810 + public int offsetByCodePoints(int index, int codePointOffset) {
8.811 + if (index < 0 || index > count) {
8.812 + throw new IndexOutOfBoundsException();
8.813 + }
8.814 + return Character.offsetByCodePointsImpl(value, offset, count,
8.815 + offset+index, codePointOffset) - offset;
8.816 + }
8.817 +
8.818 + /**
8.819 + * Copy characters from this string into dst starting at dstBegin.
8.820 + * This method doesn't perform any range checking.
8.821 + */
8.822 + void getChars(char dst[], int dstBegin) {
8.823 + System.arraycopy(value, offset, dst, dstBegin, count);
8.824 + }
8.825 +
8.826 + /**
8.827 + * Copies characters from this string into the destination character
8.828 + * array.
8.829 + * <p>
8.830 + * The first character to be copied is at index <code>srcBegin</code>;
8.831 + * the last character to be copied is at index <code>srcEnd-1</code>
8.832 + * (thus the total number of characters to be copied is
8.833 + * <code>srcEnd-srcBegin</code>). The characters are copied into the
8.834 + * subarray of <code>dst</code> starting at index <code>dstBegin</code>
8.835 + * and ending at index:
8.836 + * <p><blockquote><pre>
8.837 + * dstbegin + (srcEnd-srcBegin) - 1
8.838 + * </pre></blockquote>
8.839 + *
8.840 + * @param srcBegin index of the first character in the string
8.841 + * to copy.
8.842 + * @param srcEnd index after the last character in the string
8.843 + * to copy.
8.844 + * @param dst the destination array.
8.845 + * @param dstBegin the start offset in the destination array.
8.846 + * @exception IndexOutOfBoundsException If any of the following
8.847 + * is true:
8.848 + * <ul><li><code>srcBegin</code> is negative.
8.849 + * <li><code>srcBegin</code> is greater than <code>srcEnd</code>
8.850 + * <li><code>srcEnd</code> is greater than the length of this
8.851 + * string
8.852 + * <li><code>dstBegin</code> is negative
8.853 + * <li><code>dstBegin+(srcEnd-srcBegin)</code> is larger than
8.854 + * <code>dst.length</code></ul>
8.855 + */
8.856 + public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
8.857 + if (srcBegin < 0) {
8.858 + throw new StringIndexOutOfBoundsException(srcBegin);
8.859 + }
8.860 + if (srcEnd > count) {
8.861 + throw new StringIndexOutOfBoundsException(srcEnd);
8.862 + }
8.863 + if (srcBegin > srcEnd) {
8.864 + throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
8.865 + }
8.866 + System.arraycopy(value, offset + srcBegin, dst, dstBegin,
8.867 + srcEnd - srcBegin);
8.868 + }
8.869 +
8.870 + /**
8.871 + * Copies characters from this string into the destination byte array. Each
8.872 + * byte receives the 8 low-order bits of the corresponding character. The
8.873 + * eight high-order bits of each character are not copied and do not
8.874 + * participate in the transfer in any way.
8.875 + *
8.876 + * <p> The first character to be copied is at index {@code srcBegin}; the
8.877 + * last character to be copied is at index {@code srcEnd-1}. The total
8.878 + * number of characters to be copied is {@code srcEnd-srcBegin}. The
8.879 + * characters, converted to bytes, are copied into the subarray of {@code
8.880 + * dst} starting at index {@code dstBegin} and ending at index:
8.881 + *
8.882 + * <blockquote><pre>
8.883 + * dstbegin + (srcEnd-srcBegin) - 1
8.884 + * </pre></blockquote>
8.885 + *
8.886 + * @deprecated This method does not properly convert characters into
8.887 + * bytes. As of JDK 1.1, the preferred way to do this is via the
8.888 + * {@link #getBytes()} method, which uses the platform's default charset.
8.889 + *
8.890 + * @param srcBegin
8.891 + * Index of the first character in the string to copy
8.892 + *
8.893 + * @param srcEnd
8.894 + * Index after the last character in the string to copy
8.895 + *
8.896 + * @param dst
8.897 + * The destination array
8.898 + *
8.899 + * @param dstBegin
8.900 + * The start offset in the destination array
8.901 + *
8.902 + * @throws IndexOutOfBoundsException
8.903 + * If any of the following is true:
8.904 + * <ul>
8.905 + * <li> {@code srcBegin} is negative
8.906 + * <li> {@code srcBegin} is greater than {@code srcEnd}
8.907 + * <li> {@code srcEnd} is greater than the length of this String
8.908 + * <li> {@code dstBegin} is negative
8.909 + * <li> {@code dstBegin+(srcEnd-srcBegin)} is larger than {@code
8.910 + * dst.length}
8.911 + * </ul>
8.912 + */
8.913 + @Deprecated
8.914 + public void getBytes(int srcBegin, int srcEnd, byte dst[], int dstBegin) {
8.915 + if (srcBegin < 0) {
8.916 + throw new StringIndexOutOfBoundsException(srcBegin);
8.917 + }
8.918 + if (srcEnd > count) {
8.919 + throw new StringIndexOutOfBoundsException(srcEnd);
8.920 + }
8.921 + if (srcBegin > srcEnd) {
8.922 + throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
8.923 + }
8.924 + int j = dstBegin;
8.925 + int n = offset + srcEnd;
8.926 + int i = offset + srcBegin;
8.927 + char[] val = value; /* avoid getfield opcode */
8.928 +
8.929 + while (i < n) {
8.930 + dst[j++] = (byte)val[i++];
8.931 + }
8.932 + }
8.933 +
8.934 + /**
8.935 + * Encodes this {@code String} into a sequence of bytes using the named
8.936 + * charset, storing the result into a new byte array.
8.937 + *
8.938 + * <p> The behavior of this method when this string cannot be encoded in
8.939 + * the given charset is unspecified. The {@link
8.940 + * java.nio.charset.CharsetEncoder} class should be used when more control
8.941 + * over the encoding process is required.
8.942 + *
8.943 + * @param charsetName
8.944 + * The name of a supported {@linkplain java.nio.charset.Charset
8.945 + * charset}
8.946 + *
8.947 + * @return The resultant byte array
8.948 + *
8.949 + * @throws UnsupportedEncodingException
8.950 + * If the named charset is not supported
8.951 + *
8.952 + * @since JDK1.1
8.953 + */
8.954 + public byte[] getBytes(String charsetName)
8.955 + throws UnsupportedEncodingException
8.956 + {
8.957 + if (charsetName == null) throw new NullPointerException();
8.958 + return StringCoding.encode(charsetName, value, offset, count);
8.959 + }
8.960 +
8.961 + /**
8.962 + * Encodes this {@code String} into a sequence of bytes using the given
8.963 + * {@linkplain java.nio.charset.Charset charset}, storing the result into a
8.964 + * new byte array.
8.965 + *
8.966 + * <p> This method always replaces malformed-input and unmappable-character
8.967 + * sequences with this charset's default replacement byte array. The
8.968 + * {@link java.nio.charset.CharsetEncoder} class should be used when more
8.969 + * control over the encoding process is required.
8.970 + *
8.971 + * @param charset
8.972 + * The {@linkplain java.nio.charset.Charset} to be used to encode
8.973 + * the {@code String}
8.974 + *
8.975 + * @return The resultant byte array
8.976 + *
8.977 + * @since 1.6
8.978 + */
8.979 + public byte[] getBytes(Charset charset) {
8.980 + if (charset == null) throw new NullPointerException();
8.981 + return StringCoding.encode(charset, value, offset, count);
8.982 + }
8.983 +
8.984 + /**
8.985 + * Encodes this {@code String} into a sequence of bytes using the
8.986 + * platform's default charset, storing the result into a new byte array.
8.987 + *
8.988 + * <p> The behavior of this method when this string cannot be encoded in
8.989 + * the default charset is unspecified. The {@link
8.990 + * java.nio.charset.CharsetEncoder} class should be used when more control
8.991 + * over the encoding process is required.
8.992 + *
8.993 + * @return The resultant byte array
8.994 + *
8.995 + * @since JDK1.1
8.996 + */
8.997 + public byte[] getBytes() {
8.998 + return StringCoding.encode(value, offset, count);
8.999 + }
8.1000 +
8.1001 + /**
8.1002 + * Compares this string to the specified object. The result is {@code
8.1003 + * true} if and only if the argument is not {@code null} and is a {@code
8.1004 + * String} object that represents the same sequence of characters as this
8.1005 + * object.
8.1006 + *
8.1007 + * @param anObject
8.1008 + * The object to compare this {@code String} against
8.1009 + *
8.1010 + * @return {@code true} if the given object represents a {@code String}
8.1011 + * equivalent to this string, {@code false} otherwise
8.1012 + *
8.1013 + * @see #compareTo(String)
8.1014 + * @see #equalsIgnoreCase(String)
8.1015 + */
8.1016 + public boolean equals(Object anObject) {
8.1017 + if (this == anObject) {
8.1018 + return true;
8.1019 + }
8.1020 + if (anObject instanceof String) {
8.1021 + String anotherString = (String)anObject;
8.1022 + int n = count;
8.1023 + if (n == anotherString.count) {
8.1024 + char v1[] = value;
8.1025 + char v2[] = anotherString.value;
8.1026 + int i = offset;
8.1027 + int j = anotherString.offset;
8.1028 + while (n-- != 0) {
8.1029 + if (v1[i++] != v2[j++])
8.1030 + return false;
8.1031 + }
8.1032 + return true;
8.1033 + }
8.1034 + }
8.1035 + return false;
8.1036 + }
8.1037 +
8.1038 + /**
8.1039 + * Compares this string to the specified {@code StringBuffer}. The result
8.1040 + * is {@code true} if and only if this {@code String} represents the same
8.1041 + * sequence of characters as the specified {@code StringBuffer}.
8.1042 + *
8.1043 + * @param sb
8.1044 + * The {@code StringBuffer} to compare this {@code String} against
8.1045 + *
8.1046 + * @return {@code true} if this {@code String} represents the same
8.1047 + * sequence of characters as the specified {@code StringBuffer},
8.1048 + * {@code false} otherwise
8.1049 + *
8.1050 + * @since 1.4
8.1051 + */
8.1052 + public boolean contentEquals(StringBuffer sb) {
8.1053 + synchronized(sb) {
8.1054 + return contentEquals((CharSequence)sb);
8.1055 + }
8.1056 + }
8.1057 +
8.1058 + /**
8.1059 + * Compares this string to the specified {@code CharSequence}. The result
8.1060 + * is {@code true} if and only if this {@code String} represents the same
8.1061 + * sequence of char values as the specified sequence.
8.1062 + *
8.1063 + * @param cs
8.1064 + * The sequence to compare this {@code String} against
8.1065 + *
8.1066 + * @return {@code true} if this {@code String} represents the same
8.1067 + * sequence of char values as the specified sequence, {@code
8.1068 + * false} otherwise
8.1069 + *
8.1070 + * @since 1.5
8.1071 + */
8.1072 + public boolean contentEquals(CharSequence cs) {
8.1073 + if (count != cs.length())
8.1074 + return false;
8.1075 + // Argument is a StringBuffer, StringBuilder
8.1076 + if (cs instanceof AbstractStringBuilder) {
8.1077 + char v1[] = value;
8.1078 + char v2[] = ((AbstractStringBuilder)cs).getValue();
8.1079 + int i = offset;
8.1080 + int j = 0;
8.1081 + int n = count;
8.1082 + while (n-- != 0) {
8.1083 + if (v1[i++] != v2[j++])
8.1084 + return false;
8.1085 + }
8.1086 + return true;
8.1087 + }
8.1088 + // Argument is a String
8.1089 + if (cs.equals(this))
8.1090 + return true;
8.1091 + // Argument is a generic CharSequence
8.1092 + char v1[] = value;
8.1093 + int i = offset;
8.1094 + int j = 0;
8.1095 + int n = count;
8.1096 + while (n-- != 0) {
8.1097 + if (v1[i++] != cs.charAt(j++))
8.1098 + return false;
8.1099 + }
8.1100 + return true;
8.1101 + }
8.1102 +
8.1103 + /**
8.1104 + * Compares this {@code String} to another {@code String}, ignoring case
8.1105 + * considerations. Two strings are considered equal ignoring case if they
8.1106 + * are of the same length and corresponding characters in the two strings
8.1107 + * are equal ignoring case.
8.1108 + *
8.1109 + * <p> Two characters {@code c1} and {@code c2} are considered the same
8.1110 + * ignoring case if at least one of the following is true:
8.1111 + * <ul>
8.1112 + * <li> The two characters are the same (as compared by the
8.1113 + * {@code ==} operator)
8.1114 + * <li> Applying the method {@link
8.1115 + * java.lang.Character#toUpperCase(char)} to each character
8.1116 + * produces the same result
8.1117 + * <li> Applying the method {@link
8.1118 + * java.lang.Character#toLowerCase(char)} to each character
8.1119 + * produces the same result
8.1120 + * </ul>
8.1121 + *
8.1122 + * @param anotherString
8.1123 + * The {@code String} to compare this {@code String} against
8.1124 + *
8.1125 + * @return {@code true} if the argument is not {@code null} and it
8.1126 + * represents an equivalent {@code String} ignoring case; {@code
8.1127 + * false} otherwise
8.1128 + *
8.1129 + * @see #equals(Object)
8.1130 + */
8.1131 + public boolean equalsIgnoreCase(String anotherString) {
8.1132 + return (this == anotherString) ? true :
8.1133 + (anotherString != null) && (anotherString.count == count) &&
8.1134 + regionMatches(true, 0, anotherString, 0, count);
8.1135 + }
8.1136 +
8.1137 + /**
8.1138 + * Compares two strings lexicographically.
8.1139 + * The comparison is based on the Unicode value of each character in
8.1140 + * the strings. The character sequence represented by this
8.1141 + * <code>String</code> object is compared lexicographically to the
8.1142 + * character sequence represented by the argument string. The result is
8.1143 + * a negative integer if this <code>String</code> object
8.1144 + * lexicographically precedes the argument string. The result is a
8.1145 + * positive integer if this <code>String</code> object lexicographically
8.1146 + * follows the argument string. The result is zero if the strings
8.1147 + * are equal; <code>compareTo</code> returns <code>0</code> exactly when
8.1148 + * the {@link #equals(Object)} method would return <code>true</code>.
8.1149 + * <p>
8.1150 + * This is the definition of lexicographic ordering. If two strings are
8.1151 + * different, then either they have different characters at some index
8.1152 + * that is a valid index for both strings, or their lengths are different,
8.1153 + * or both. If they have different characters at one or more index
8.1154 + * positions, let <i>k</i> be the smallest such index; then the string
8.1155 + * whose character at position <i>k</i> has the smaller value, as
8.1156 + * determined by using the < operator, lexicographically precedes the
8.1157 + * other string. In this case, <code>compareTo</code> returns the
8.1158 + * difference of the two character values at position <code>k</code> in
8.1159 + * the two string -- that is, the value:
8.1160 + * <blockquote><pre>
8.1161 + * this.charAt(k)-anotherString.charAt(k)
8.1162 + * </pre></blockquote>
8.1163 + * If there is no index position at which they differ, then the shorter
8.1164 + * string lexicographically precedes the longer string. In this case,
8.1165 + * <code>compareTo</code> returns the difference of the lengths of the
8.1166 + * strings -- that is, the value:
8.1167 + * <blockquote><pre>
8.1168 + * this.length()-anotherString.length()
8.1169 + * </pre></blockquote>
8.1170 + *
8.1171 + * @param anotherString the <code>String</code> to be compared.
8.1172 + * @return the value <code>0</code> if the argument string is equal to
8.1173 + * this string; a value less than <code>0</code> if this string
8.1174 + * is lexicographically less than the string argument; and a
8.1175 + * value greater than <code>0</code> if this string is
8.1176 + * lexicographically greater than the string argument.
8.1177 + */
8.1178 + public int compareTo(String anotherString) {
8.1179 + int len1 = count;
8.1180 + int len2 = anotherString.count;
8.1181 + int n = Math.min(len1, len2);
8.1182 + char v1[] = value;
8.1183 + char v2[] = anotherString.value;
8.1184 + int i = offset;
8.1185 + int j = anotherString.offset;
8.1186 +
8.1187 + if (i == j) {
8.1188 + int k = i;
8.1189 + int lim = n + i;
8.1190 + while (k < lim) {
8.1191 + char c1 = v1[k];
8.1192 + char c2 = v2[k];
8.1193 + if (c1 != c2) {
8.1194 + return c1 - c2;
8.1195 + }
8.1196 + k++;
8.1197 + }
8.1198 + } else {
8.1199 + while (n-- != 0) {
8.1200 + char c1 = v1[i++];
8.1201 + char c2 = v2[j++];
8.1202 + if (c1 != c2) {
8.1203 + return c1 - c2;
8.1204 + }
8.1205 + }
8.1206 + }
8.1207 + return len1 - len2;
8.1208 + }
8.1209 +
8.1210 + /**
8.1211 + * A Comparator that orders <code>String</code> objects as by
8.1212 + * <code>compareToIgnoreCase</code>. This comparator is serializable.
8.1213 + * <p>
8.1214 + * Note that this Comparator does <em>not</em> take locale into account,
8.1215 + * and will result in an unsatisfactory ordering for certain locales.
8.1216 + * The java.text package provides <em>Collators</em> to allow
8.1217 + * locale-sensitive ordering.
8.1218 + *
8.1219 + * @see java.text.Collator#compare(String, String)
8.1220 + * @since 1.2
8.1221 + */
8.1222 + public static final Comparator<String> CASE_INSENSITIVE_ORDER
8.1223 + = new CaseInsensitiveComparator();
8.1224 + private static class CaseInsensitiveComparator
8.1225 + implements Comparator<String>, java.io.Serializable {
8.1226 + // use serialVersionUID from JDK 1.2.2 for interoperability
8.1227 + private static final long serialVersionUID = 8575799808933029326L;
8.1228 +
8.1229 + public int compare(String s1, String s2) {
8.1230 + int n1 = s1.length();
8.1231 + int n2 = s2.length();
8.1232 + int min = Math.min(n1, n2);
8.1233 + for (int i = 0; i < min; i++) {
8.1234 + char c1 = s1.charAt(i);
8.1235 + char c2 = s2.charAt(i);
8.1236 + if (c1 != c2) {
8.1237 + c1 = Character.toUpperCase(c1);
8.1238 + c2 = Character.toUpperCase(c2);
8.1239 + if (c1 != c2) {
8.1240 + c1 = Character.toLowerCase(c1);
8.1241 + c2 = Character.toLowerCase(c2);
8.1242 + if (c1 != c2) {
8.1243 + // No overflow because of numeric promotion
8.1244 + return c1 - c2;
8.1245 + }
8.1246 + }
8.1247 + }
8.1248 + }
8.1249 + return n1 - n2;
8.1250 + }
8.1251 + }
8.1252 +
8.1253 + /**
8.1254 + * Compares two strings lexicographically, ignoring case
8.1255 + * differences. This method returns an integer whose sign is that of
8.1256 + * calling <code>compareTo</code> with normalized versions of the strings
8.1257 + * where case differences have been eliminated by calling
8.1258 + * <code>Character.toLowerCase(Character.toUpperCase(character))</code> on
8.1259 + * each character.
8.1260 + * <p>
8.1261 + * Note that this method does <em>not</em> take locale into account,
8.1262 + * and will result in an unsatisfactory ordering for certain locales.
8.1263 + * The java.text package provides <em>collators</em> to allow
8.1264 + * locale-sensitive ordering.
8.1265 + *
8.1266 + * @param str the <code>String</code> to be compared.
8.1267 + * @return a negative integer, zero, or a positive integer as the
8.1268 + * specified String is greater than, equal to, or less
8.1269 + * than this String, ignoring case considerations.
8.1270 + * @see java.text.Collator#compare(String, String)
8.1271 + * @since 1.2
8.1272 + */
8.1273 + public int compareToIgnoreCase(String str) {
8.1274 + return CASE_INSENSITIVE_ORDER.compare(this, str);
8.1275 + }
8.1276 +
8.1277 + /**
8.1278 + * Tests if two string regions are equal.
8.1279 + * <p>
8.1280 + * A substring of this <tt>String</tt> object is compared to a substring
8.1281 + * of the argument other. The result is true if these substrings
8.1282 + * represent identical character sequences. The substring of this
8.1283 + * <tt>String</tt> object to be compared begins at index <tt>toffset</tt>
8.1284 + * and has length <tt>len</tt>. The substring of other to be compared
8.1285 + * begins at index <tt>ooffset</tt> and has length <tt>len</tt>. The
8.1286 + * result is <tt>false</tt> if and only if at least one of the following
8.1287 + * is true:
8.1288 + * <ul><li><tt>toffset</tt> is negative.
8.1289 + * <li><tt>ooffset</tt> is negative.
8.1290 + * <li><tt>toffset+len</tt> is greater than the length of this
8.1291 + * <tt>String</tt> object.
8.1292 + * <li><tt>ooffset+len</tt> is greater than the length of the other
8.1293 + * argument.
8.1294 + * <li>There is some nonnegative integer <i>k</i> less than <tt>len</tt>
8.1295 + * such that:
8.1296 + * <tt>this.charAt(toffset+<i>k</i>) != other.charAt(ooffset+<i>k</i>)</tt>
8.1297 + * </ul>
8.1298 + *
8.1299 + * @param toffset the starting offset of the subregion in this string.
8.1300 + * @param other the string argument.
8.1301 + * @param ooffset the starting offset of the subregion in the string
8.1302 + * argument.
8.1303 + * @param len the number of characters to compare.
8.1304 + * @return <code>true</code> if the specified subregion of this string
8.1305 + * exactly matches the specified subregion of the string argument;
8.1306 + * <code>false</code> otherwise.
8.1307 + */
8.1308 + public boolean regionMatches(int toffset, String other, int ooffset,
8.1309 + int len) {
8.1310 + char ta[] = value;
8.1311 + int to = offset + toffset;
8.1312 + char pa[] = other.value;
8.1313 + int po = other.offset + ooffset;
8.1314 + // Note: toffset, ooffset, or len might be near -1>>>1.
8.1315 + if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len)
8.1316 + || (ooffset > (long)other.count - len)) {
8.1317 + return false;
8.1318 + }
8.1319 + while (len-- > 0) {
8.1320 + if (ta[to++] != pa[po++]) {
8.1321 + return false;
8.1322 + }
8.1323 + }
8.1324 + return true;
8.1325 + }
8.1326 +
8.1327 + /**
8.1328 + * Tests if two string regions are equal.
8.1329 + * <p>
8.1330 + * A substring of this <tt>String</tt> object is compared to a substring
8.1331 + * of the argument <tt>other</tt>. The result is <tt>true</tt> if these
8.1332 + * substrings represent character sequences that are the same, ignoring
8.1333 + * case if and only if <tt>ignoreCase</tt> is true. The substring of
8.1334 + * this <tt>String</tt> object to be compared begins at index
8.1335 + * <tt>toffset</tt> and has length <tt>len</tt>. The substring of
8.1336 + * <tt>other</tt> to be compared begins at index <tt>ooffset</tt> and
8.1337 + * has length <tt>len</tt>. The result is <tt>false</tt> if and only if
8.1338 + * at least one of the following is true:
8.1339 + * <ul><li><tt>toffset</tt> is negative.
8.1340 + * <li><tt>ooffset</tt> is negative.
8.1341 + * <li><tt>toffset+len</tt> is greater than the length of this
8.1342 + * <tt>String</tt> object.
8.1343 + * <li><tt>ooffset+len</tt> is greater than the length of the other
8.1344 + * argument.
8.1345 + * <li><tt>ignoreCase</tt> is <tt>false</tt> and there is some nonnegative
8.1346 + * integer <i>k</i> less than <tt>len</tt> such that:
8.1347 + * <blockquote><pre>
8.1348 + * this.charAt(toffset+k) != other.charAt(ooffset+k)
8.1349 + * </pre></blockquote>
8.1350 + * <li><tt>ignoreCase</tt> is <tt>true</tt> and there is some nonnegative
8.1351 + * integer <i>k</i> less than <tt>len</tt> such that:
8.1352 + * <blockquote><pre>
8.1353 + * Character.toLowerCase(this.charAt(toffset+k)) !=
8.1354 + Character.toLowerCase(other.charAt(ooffset+k))
8.1355 + * </pre></blockquote>
8.1356 + * and:
8.1357 + * <blockquote><pre>
8.1358 + * Character.toUpperCase(this.charAt(toffset+k)) !=
8.1359 + * Character.toUpperCase(other.charAt(ooffset+k))
8.1360 + * </pre></blockquote>
8.1361 + * </ul>
8.1362 + *
8.1363 + * @param ignoreCase if <code>true</code>, ignore case when comparing
8.1364 + * characters.
8.1365 + * @param toffset the starting offset of the subregion in this
8.1366 + * string.
8.1367 + * @param other the string argument.
8.1368 + * @param ooffset the starting offset of the subregion in the string
8.1369 + * argument.
8.1370 + * @param len the number of characters to compare.
8.1371 + * @return <code>true</code> if the specified subregion of this string
8.1372 + * matches the specified subregion of the string argument;
8.1373 + * <code>false</code> otherwise. Whether the matching is exact
8.1374 + * or case insensitive depends on the <code>ignoreCase</code>
8.1375 + * argument.
8.1376 + */
8.1377 + public boolean regionMatches(boolean ignoreCase, int toffset,
8.1378 + String other, int ooffset, int len) {
8.1379 + char ta[] = value;
8.1380 + int to = offset + toffset;
8.1381 + char pa[] = other.value;
8.1382 + int po = other.offset + ooffset;
8.1383 + // Note: toffset, ooffset, or len might be near -1>>>1.
8.1384 + if ((ooffset < 0) || (toffset < 0) || (toffset > (long)count - len) ||
8.1385 + (ooffset > (long)other.count - len)) {
8.1386 + return false;
8.1387 + }
8.1388 + while (len-- > 0) {
8.1389 + char c1 = ta[to++];
8.1390 + char c2 = pa[po++];
8.1391 + if (c1 == c2) {
8.1392 + continue;
8.1393 + }
8.1394 + if (ignoreCase) {
8.1395 + // If characters don't match but case may be ignored,
8.1396 + // try converting both characters to uppercase.
8.1397 + // If the results match, then the comparison scan should
8.1398 + // continue.
8.1399 + char u1 = Character.toUpperCase(c1);
8.1400 + char u2 = Character.toUpperCase(c2);
8.1401 + if (u1 == u2) {
8.1402 + continue;
8.1403 + }
8.1404 + // Unfortunately, conversion to uppercase does not work properly
8.1405 + // for the Georgian alphabet, which has strange rules about case
8.1406 + // conversion. So we need to make one last check before
8.1407 + // exiting.
8.1408 + if (Character.toLowerCase(u1) == Character.toLowerCase(u2)) {
8.1409 + continue;
8.1410 + }
8.1411 + }
8.1412 + return false;
8.1413 + }
8.1414 + return true;
8.1415 + }
8.1416 +
8.1417 + /**
8.1418 + * Tests if the substring of this string beginning at the
8.1419 + * specified index starts with the specified prefix.
8.1420 + *
8.1421 + * @param prefix the prefix.
8.1422 + * @param toffset where to begin looking in this string.
8.1423 + * @return <code>true</code> if the character sequence represented by the
8.1424 + * argument is a prefix of the substring of this object starting
8.1425 + * at index <code>toffset</code>; <code>false</code> otherwise.
8.1426 + * The result is <code>false</code> if <code>toffset</code> is
8.1427 + * negative or greater than the length of this
8.1428 + * <code>String</code> object; otherwise the result is the same
8.1429 + * as the result of the expression
8.1430 + * <pre>
8.1431 + * this.substring(toffset).startsWith(prefix)
8.1432 + * </pre>
8.1433 + */
8.1434 + public boolean startsWith(String prefix, int toffset) {
8.1435 + char ta[] = value;
8.1436 + int to = offset + toffset;
8.1437 + char pa[] = prefix.value;
8.1438 + int po = prefix.offset;
8.1439 + int pc = prefix.count;
8.1440 + // Note: toffset might be near -1>>>1.
8.1441 + if ((toffset < 0) || (toffset > count - pc)) {
8.1442 + return false;
8.1443 + }
8.1444 + while (--pc >= 0) {
8.1445 + if (ta[to++] != pa[po++]) {
8.1446 + return false;
8.1447 + }
8.1448 + }
8.1449 + return true;
8.1450 + }
8.1451 +
8.1452 + /**
8.1453 + * Tests if this string starts with the specified prefix.
8.1454 + *
8.1455 + * @param prefix the prefix.
8.1456 + * @return <code>true</code> if the character sequence represented by the
8.1457 + * argument is a prefix of the character sequence represented by
8.1458 + * this string; <code>false</code> otherwise.
8.1459 + * Note also that <code>true</code> will be returned if the
8.1460 + * argument is an empty string or is equal to this
8.1461 + * <code>String</code> object as determined by the
8.1462 + * {@link #equals(Object)} method.
8.1463 + * @since 1. 0
8.1464 + */
8.1465 + public boolean startsWith(String prefix) {
8.1466 + return startsWith(prefix, 0);
8.1467 + }
8.1468 +
8.1469 + /**
8.1470 + * Tests if this string ends with the specified suffix.
8.1471 + *
8.1472 + * @param suffix the suffix.
8.1473 + * @return <code>true</code> if the character sequence represented by the
8.1474 + * argument is a suffix of the character sequence represented by
8.1475 + * this object; <code>false</code> otherwise. Note that the
8.1476 + * result will be <code>true</code> if the argument is the
8.1477 + * empty string or is equal to this <code>String</code> object
8.1478 + * as determined by the {@link #equals(Object)} method.
8.1479 + */
8.1480 + public boolean endsWith(String suffix) {
8.1481 + return startsWith(suffix, count - suffix.count);
8.1482 + }
8.1483 +
8.1484 + /**
8.1485 + * Returns a hash code for this string. The hash code for a
8.1486 + * <code>String</code> object is computed as
8.1487 + * <blockquote><pre>
8.1488 + * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
8.1489 + * </pre></blockquote>
8.1490 + * using <code>int</code> arithmetic, where <code>s[i]</code> is the
8.1491 + * <i>i</i>th character of the string, <code>n</code> is the length of
8.1492 + * the string, and <code>^</code> indicates exponentiation.
8.1493 + * (The hash value of the empty string is zero.)
8.1494 + *
8.1495 + * @return a hash code value for this object.
8.1496 + */
8.1497 + public int hashCode() {
8.1498 + int h = hash;
8.1499 + if (h == 0 && count > 0) {
8.1500 + int off = offset;
8.1501 + char val[] = value;
8.1502 + int len = count;
8.1503 +
8.1504 + for (int i = 0; i < len; i++) {
8.1505 + h = 31*h + val[off++];
8.1506 + }
8.1507 + hash = h;
8.1508 + }
8.1509 + return h;
8.1510 + }
8.1511 +
8.1512 + /**
8.1513 + * Returns the index within this string of the first occurrence of
8.1514 + * the specified character. If a character with value
8.1515 + * <code>ch</code> occurs in the character sequence represented by
8.1516 + * this <code>String</code> object, then the index (in Unicode
8.1517 + * code units) of the first such occurrence is returned. For
8.1518 + * values of <code>ch</code> in the range from 0 to 0xFFFF
8.1519 + * (inclusive), this is the smallest value <i>k</i> such that:
8.1520 + * <blockquote><pre>
8.1521 + * this.charAt(<i>k</i>) == ch
8.1522 + * </pre></blockquote>
8.1523 + * is true. For other values of <code>ch</code>, it is the
8.1524 + * smallest value <i>k</i> such that:
8.1525 + * <blockquote><pre>
8.1526 + * this.codePointAt(<i>k</i>) == ch
8.1527 + * </pre></blockquote>
8.1528 + * is true. In either case, if no such character occurs in this
8.1529 + * string, then <code>-1</code> is returned.
8.1530 + *
8.1531 + * @param ch a character (Unicode code point).
8.1532 + * @return the index of the first occurrence of the character in the
8.1533 + * character sequence represented by this object, or
8.1534 + * <code>-1</code> if the character does not occur.
8.1535 + */
8.1536 + public int indexOf(int ch) {
8.1537 + return indexOf(ch, 0);
8.1538 + }
8.1539 +
8.1540 + /**
8.1541 + * Returns the index within this string of the first occurrence of the
8.1542 + * specified character, starting the search at the specified index.
8.1543 + * <p>
8.1544 + * If a character with value <code>ch</code> occurs in the
8.1545 + * character sequence represented by this <code>String</code>
8.1546 + * object at an index no smaller than <code>fromIndex</code>, then
8.1547 + * the index of the first such occurrence is returned. For values
8.1548 + * of <code>ch</code> in the range from 0 to 0xFFFF (inclusive),
8.1549 + * this is the smallest value <i>k</i> such that:
8.1550 + * <blockquote><pre>
8.1551 + * (this.charAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
8.1552 + * </pre></blockquote>
8.1553 + * is true. For other values of <code>ch</code>, it is the
8.1554 + * smallest value <i>k</i> such that:
8.1555 + * <blockquote><pre>
8.1556 + * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> >= fromIndex)
8.1557 + * </pre></blockquote>
8.1558 + * is true. In either case, if no such character occurs in this
8.1559 + * string at or after position <code>fromIndex</code>, then
8.1560 + * <code>-1</code> is returned.
8.1561 + *
8.1562 + * <p>
8.1563 + * There is no restriction on the value of <code>fromIndex</code>. If it
8.1564 + * is negative, it has the same effect as if it were zero: this entire
8.1565 + * string may be searched. If it is greater than the length of this
8.1566 + * string, it has the same effect as if it were equal to the length of
8.1567 + * this string: <code>-1</code> is returned.
8.1568 + *
8.1569 + * <p>All indices are specified in <code>char</code> values
8.1570 + * (Unicode code units).
8.1571 + *
8.1572 + * @param ch a character (Unicode code point).
8.1573 + * @param fromIndex the index to start the search from.
8.1574 + * @return the index of the first occurrence of the character in the
8.1575 + * character sequence represented by this object that is greater
8.1576 + * than or equal to <code>fromIndex</code>, or <code>-1</code>
8.1577 + * if the character does not occur.
8.1578 + */
8.1579 + public int indexOf(int ch, int fromIndex) {
8.1580 + if (fromIndex < 0) {
8.1581 + fromIndex = 0;
8.1582 + } else if (fromIndex >= count) {
8.1583 + // Note: fromIndex might be near -1>>>1.
8.1584 + return -1;
8.1585 + }
8.1586 +
8.1587 + if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
8.1588 + // handle most cases here (ch is a BMP code point or a
8.1589 + // negative value (invalid code point))
8.1590 + final char[] value = this.value;
8.1591 + final int offset = this.offset;
8.1592 + final int max = offset + count;
8.1593 + for (int i = offset + fromIndex; i < max ; i++) {
8.1594 + if (value[i] == ch) {
8.1595 + return i - offset;
8.1596 + }
8.1597 + }
8.1598 + return -1;
8.1599 + } else {
8.1600 + return indexOfSupplementary(ch, fromIndex);
8.1601 + }
8.1602 + }
8.1603 +
8.1604 + /**
8.1605 + * Handles (rare) calls of indexOf with a supplementary character.
8.1606 + */
8.1607 + private int indexOfSupplementary(int ch, int fromIndex) {
8.1608 + if (Character.isValidCodePoint(ch)) {
8.1609 + final char[] value = this.value;
8.1610 + final int offset = this.offset;
8.1611 + final char hi = Character.highSurrogate(ch);
8.1612 + final char lo = Character.lowSurrogate(ch);
8.1613 + final int max = offset + count - 1;
8.1614 + for (int i = offset + fromIndex; i < max; i++) {
8.1615 + if (value[i] == hi && value[i+1] == lo) {
8.1616 + return i - offset;
8.1617 + }
8.1618 + }
8.1619 + }
8.1620 + return -1;
8.1621 + }
8.1622 +
8.1623 + /**
8.1624 + * Returns the index within this string of the last occurrence of
8.1625 + * the specified character. For values of <code>ch</code> in the
8.1626 + * range from 0 to 0xFFFF (inclusive), the index (in Unicode code
8.1627 + * units) returned is the largest value <i>k</i> such that:
8.1628 + * <blockquote><pre>
8.1629 + * this.charAt(<i>k</i>) == ch
8.1630 + * </pre></blockquote>
8.1631 + * is true. For other values of <code>ch</code>, it is the
8.1632 + * largest value <i>k</i> such that:
8.1633 + * <blockquote><pre>
8.1634 + * this.codePointAt(<i>k</i>) == ch
8.1635 + * </pre></blockquote>
8.1636 + * is true. In either case, if no such character occurs in this
8.1637 + * string, then <code>-1</code> is returned. The
8.1638 + * <code>String</code> is searched backwards starting at the last
8.1639 + * character.
8.1640 + *
8.1641 + * @param ch a character (Unicode code point).
8.1642 + * @return the index of the last occurrence of the character in the
8.1643 + * character sequence represented by this object, or
8.1644 + * <code>-1</code> if the character does not occur.
8.1645 + */
8.1646 + public int lastIndexOf(int ch) {
8.1647 + return lastIndexOf(ch, count - 1);
8.1648 + }
8.1649 +
8.1650 + /**
8.1651 + * Returns the index within this string of the last occurrence of
8.1652 + * the specified character, searching backward starting at the
8.1653 + * specified index. For values of <code>ch</code> in the range
8.1654 + * from 0 to 0xFFFF (inclusive), the index returned is the largest
8.1655 + * value <i>k</i> such that:
8.1656 + * <blockquote><pre>
8.1657 + * (this.charAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
8.1658 + * </pre></blockquote>
8.1659 + * is true. For other values of <code>ch</code>, it is the
8.1660 + * largest value <i>k</i> such that:
8.1661 + * <blockquote><pre>
8.1662 + * (this.codePointAt(<i>k</i>) == ch) && (<i>k</i> <= fromIndex)
8.1663 + * </pre></blockquote>
8.1664 + * is true. In either case, if no such character occurs in this
8.1665 + * string at or before position <code>fromIndex</code>, then
8.1666 + * <code>-1</code> is returned.
8.1667 + *
8.1668 + * <p>All indices are specified in <code>char</code> values
8.1669 + * (Unicode code units).
8.1670 + *
8.1671 + * @param ch a character (Unicode code point).
8.1672 + * @param fromIndex the index to start the search from. There is no
8.1673 + * restriction on the value of <code>fromIndex</code>. If it is
8.1674 + * greater than or equal to the length of this string, it has
8.1675 + * the same effect as if it were equal to one less than the
8.1676 + * length of this string: this entire string may be searched.
8.1677 + * If it is negative, it has the same effect as if it were -1:
8.1678 + * -1 is returned.
8.1679 + * @return the index of the last occurrence of the character in the
8.1680 + * character sequence represented by this object that is less
8.1681 + * than or equal to <code>fromIndex</code>, or <code>-1</code>
8.1682 + * if the character does not occur before that point.
8.1683 + */
8.1684 + public int lastIndexOf(int ch, int fromIndex) {
8.1685 + if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
8.1686 + // handle most cases here (ch is a BMP code point or a
8.1687 + // negative value (invalid code point))
8.1688 + final char[] value = this.value;
8.1689 + final int offset = this.offset;
8.1690 + int i = offset + Math.min(fromIndex, count - 1);
8.1691 + for (; i >= offset ; i--) {
8.1692 + if (value[i] == ch) {
8.1693 + return i - offset;
8.1694 + }
8.1695 + }
8.1696 + return -1;
8.1697 + } else {
8.1698 + return lastIndexOfSupplementary(ch, fromIndex);
8.1699 + }
8.1700 + }
8.1701 +
8.1702 + /**
8.1703 + * Handles (rare) calls of lastIndexOf with a supplementary character.
8.1704 + */
8.1705 + private int lastIndexOfSupplementary(int ch, int fromIndex) {
8.1706 + if (Character.isValidCodePoint(ch)) {
8.1707 + final char[] value = this.value;
8.1708 + final int offset = this.offset;
8.1709 + char hi = Character.highSurrogate(ch);
8.1710 + char lo = Character.lowSurrogate(ch);
8.1711 + int i = offset + Math.min(fromIndex, count - 2);
8.1712 + for (; i >= offset; i--) {
8.1713 + if (value[i] == hi && value[i+1] == lo) {
8.1714 + return i - offset;
8.1715 + }
8.1716 + }
8.1717 + }
8.1718 + return -1;
8.1719 + }
8.1720 +
8.1721 + /**
8.1722 + * Returns the index within this string of the first occurrence of the
8.1723 + * specified substring.
8.1724 + *
8.1725 + * <p>The returned index is the smallest value <i>k</i> for which:
8.1726 + * <blockquote><pre>
8.1727 + * this.startsWith(str, <i>k</i>)
8.1728 + * </pre></blockquote>
8.1729 + * If no such value of <i>k</i> exists, then {@code -1} is returned.
8.1730 + *
8.1731 + * @param str the substring to search for.
8.1732 + * @return the index of the first occurrence of the specified substring,
8.1733 + * or {@code -1} if there is no such occurrence.
8.1734 + */
8.1735 + public int indexOf(String str) {
8.1736 + return indexOf(str, 0);
8.1737 + }
8.1738 +
8.1739 + /**
8.1740 + * Returns the index within this string of the first occurrence of the
8.1741 + * specified substring, starting at the specified index.
8.1742 + *
8.1743 + * <p>The returned index is the smallest value <i>k</i> for which:
8.1744 + * <blockquote><pre>
8.1745 + * <i>k</i> >= fromIndex && this.startsWith(str, <i>k</i>)
8.1746 + * </pre></blockquote>
8.1747 + * If no such value of <i>k</i> exists, then {@code -1} is returned.
8.1748 + *
8.1749 + * @param str the substring to search for.
8.1750 + * @param fromIndex the index from which to start the search.
8.1751 + * @return the index of the first occurrence of the specified substring,
8.1752 + * starting at the specified index,
8.1753 + * or {@code -1} if there is no such occurrence.
8.1754 + */
8.1755 + public int indexOf(String str, int fromIndex) {
8.1756 + return indexOf(value, offset, count,
8.1757 + str.value, str.offset, str.count, fromIndex);
8.1758 + }
8.1759 +
8.1760 + /**
8.1761 + * Code shared by String and StringBuffer to do searches. The
8.1762 + * source is the character array being searched, and the target
8.1763 + * is the string being searched for.
8.1764 + *
8.1765 + * @param source the characters being searched.
8.1766 + * @param sourceOffset offset of the source string.
8.1767 + * @param sourceCount count of the source string.
8.1768 + * @param target the characters being searched for.
8.1769 + * @param targetOffset offset of the target string.
8.1770 + * @param targetCount count of the target string.
8.1771 + * @param fromIndex the index to begin searching from.
8.1772 + */
8.1773 + static int indexOf(char[] source, int sourceOffset, int sourceCount,
8.1774 + char[] target, int targetOffset, int targetCount,
8.1775 + int fromIndex) {
8.1776 + if (fromIndex >= sourceCount) {
8.1777 + return (targetCount == 0 ? sourceCount : -1);
8.1778 + }
8.1779 + if (fromIndex < 0) {
8.1780 + fromIndex = 0;
8.1781 + }
8.1782 + if (targetCount == 0) {
8.1783 + return fromIndex;
8.1784 + }
8.1785 +
8.1786 + char first = target[targetOffset];
8.1787 + int max = sourceOffset + (sourceCount - targetCount);
8.1788 +
8.1789 + for (int i = sourceOffset + fromIndex; i <= max; i++) {
8.1790 + /* Look for first character. */
8.1791 + if (source[i] != first) {
8.1792 + while (++i <= max && source[i] != first);
8.1793 + }
8.1794 +
8.1795 + /* Found first character, now look at the rest of v2 */
8.1796 + if (i <= max) {
8.1797 + int j = i + 1;
8.1798 + int end = j + targetCount - 1;
8.1799 + for (int k = targetOffset + 1; j < end && source[j] ==
8.1800 + target[k]; j++, k++);
8.1801 +
8.1802 + if (j == end) {
8.1803 + /* Found whole string. */
8.1804 + return i - sourceOffset;
8.1805 + }
8.1806 + }
8.1807 + }
8.1808 + return -1;
8.1809 + }
8.1810 +
8.1811 + /**
8.1812 + * Returns the index within this string of the last occurrence of the
8.1813 + * specified substring. The last occurrence of the empty string ""
8.1814 + * is considered to occur at the index value {@code this.length()}.
8.1815 + *
8.1816 + * <p>The returned index is the largest value <i>k</i> for which:
8.1817 + * <blockquote><pre>
8.1818 + * this.startsWith(str, <i>k</i>)
8.1819 + * </pre></blockquote>
8.1820 + * If no such value of <i>k</i> exists, then {@code -1} is returned.
8.1821 + *
8.1822 + * @param str the substring to search for.
8.1823 + * @return the index of the last occurrence of the specified substring,
8.1824 + * or {@code -1} if there is no such occurrence.
8.1825 + */
8.1826 + public int lastIndexOf(String str) {
8.1827 + return lastIndexOf(str, count);
8.1828 + }
8.1829 +
8.1830 + /**
8.1831 + * Returns the index within this string of the last occurrence of the
8.1832 + * specified substring, searching backward starting at the specified index.
8.1833 + *
8.1834 + * <p>The returned index is the largest value <i>k</i> for which:
8.1835 + * <blockquote><pre>
8.1836 + * <i>k</i> <= fromIndex && this.startsWith(str, <i>k</i>)
8.1837 + * </pre></blockquote>
8.1838 + * If no such value of <i>k</i> exists, then {@code -1} is returned.
8.1839 + *
8.1840 + * @param str the substring to search for.
8.1841 + * @param fromIndex the index to start the search from.
8.1842 + * @return the index of the last occurrence of the specified substring,
8.1843 + * searching backward from the specified index,
8.1844 + * or {@code -1} if there is no such occurrence.
8.1845 + */
8.1846 + public int lastIndexOf(String str, int fromIndex) {
8.1847 + return lastIndexOf(value, offset, count,
8.1848 + str.value, str.offset, str.count, fromIndex);
8.1849 + }
8.1850 +
8.1851 + /**
8.1852 + * Code shared by String and StringBuffer to do searches. The
8.1853 + * source is the character array being searched, and the target
8.1854 + * is the string being searched for.
8.1855 + *
8.1856 + * @param source the characters being searched.
8.1857 + * @param sourceOffset offset of the source string.
8.1858 + * @param sourceCount count of the source string.
8.1859 + * @param target the characters being searched for.
8.1860 + * @param targetOffset offset of the target string.
8.1861 + * @param targetCount count of the target string.
8.1862 + * @param fromIndex the index to begin searching from.
8.1863 + */
8.1864 + static int lastIndexOf(char[] source, int sourceOffset, int sourceCount,
8.1865 + char[] target, int targetOffset, int targetCount,
8.1866 + int fromIndex) {
8.1867 + /*
8.1868 + * Check arguments; return immediately where possible. For
8.1869 + * consistency, don't check for null str.
8.1870 + */
8.1871 + int rightIndex = sourceCount - targetCount;
8.1872 + if (fromIndex < 0) {
8.1873 + return -1;
8.1874 + }
8.1875 + if (fromIndex > rightIndex) {
8.1876 + fromIndex = rightIndex;
8.1877 + }
8.1878 + /* Empty string always matches. */
8.1879 + if (targetCount == 0) {
8.1880 + return fromIndex;
8.1881 + }
8.1882 +
8.1883 + int strLastIndex = targetOffset + targetCount - 1;
8.1884 + char strLastChar = target[strLastIndex];
8.1885 + int min = sourceOffset + targetCount - 1;
8.1886 + int i = min + fromIndex;
8.1887 +
8.1888 + startSearchForLastChar:
8.1889 + while (true) {
8.1890 + while (i >= min && source[i] != strLastChar) {
8.1891 + i--;
8.1892 + }
8.1893 + if (i < min) {
8.1894 + return -1;
8.1895 + }
8.1896 + int j = i - 1;
8.1897 + int start = j - (targetCount - 1);
8.1898 + int k = strLastIndex - 1;
8.1899 +
8.1900 + while (j > start) {
8.1901 + if (source[j--] != target[k--]) {
8.1902 + i--;
8.1903 + continue startSearchForLastChar;
8.1904 + }
8.1905 + }
8.1906 + return start - sourceOffset + 1;
8.1907 + }
8.1908 + }
8.1909 +
8.1910 + /**
8.1911 + * Returns a new string that is a substring of this string. The
8.1912 + * substring begins with the character at the specified index and
8.1913 + * extends to the end of this string. <p>
8.1914 + * Examples:
8.1915 + * <blockquote><pre>
8.1916 + * "unhappy".substring(2) returns "happy"
8.1917 + * "Harbison".substring(3) returns "bison"
8.1918 + * "emptiness".substring(9) returns "" (an empty string)
8.1919 + * </pre></blockquote>
8.1920 + *
8.1921 + * @param beginIndex the beginning index, inclusive.
8.1922 + * @return the specified substring.
8.1923 + * @exception IndexOutOfBoundsException if
8.1924 + * <code>beginIndex</code> is negative or larger than the
8.1925 + * length of this <code>String</code> object.
8.1926 + */
8.1927 + public String substring(int beginIndex) {
8.1928 + return substring(beginIndex, count);
8.1929 + }
8.1930 +
8.1931 + /**
8.1932 + * Returns a new string that is a substring of this string. The
8.1933 + * substring begins at the specified <code>beginIndex</code> and
8.1934 + * extends to the character at index <code>endIndex - 1</code>.
8.1935 + * Thus the length of the substring is <code>endIndex-beginIndex</code>.
8.1936 + * <p>
8.1937 + * Examples:
8.1938 + * <blockquote><pre>
8.1939 + * "hamburger".substring(4, 8) returns "urge"
8.1940 + * "smiles".substring(1, 5) returns "mile"
8.1941 + * </pre></blockquote>
8.1942 + *
8.1943 + * @param beginIndex the beginning index, inclusive.
8.1944 + * @param endIndex the ending index, exclusive.
8.1945 + * @return the specified substring.
8.1946 + * @exception IndexOutOfBoundsException if the
8.1947 + * <code>beginIndex</code> is negative, or
8.1948 + * <code>endIndex</code> is larger than the length of
8.1949 + * this <code>String</code> object, or
8.1950 + * <code>beginIndex</code> is larger than
8.1951 + * <code>endIndex</code>.
8.1952 + */
8.1953 + public String substring(int beginIndex, int endIndex) {
8.1954 + if (beginIndex < 0) {
8.1955 + throw new StringIndexOutOfBoundsException(beginIndex);
8.1956 + }
8.1957 + if (endIndex > count) {
8.1958 + throw new StringIndexOutOfBoundsException(endIndex);
8.1959 + }
8.1960 + if (beginIndex > endIndex) {
8.1961 + throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
8.1962 + }
8.1963 + return ((beginIndex == 0) && (endIndex == count)) ? this :
8.1964 + new String(offset + beginIndex, endIndex - beginIndex, value);
8.1965 + }
8.1966 +
8.1967 + /**
8.1968 + * Returns a new character sequence that is a subsequence of this sequence.
8.1969 + *
8.1970 + * <p> An invocation of this method of the form
8.1971 + *
8.1972 + * <blockquote><pre>
8.1973 + * str.subSequence(begin, end)</pre></blockquote>
8.1974 + *
8.1975 + * behaves in exactly the same way as the invocation
8.1976 + *
8.1977 + * <blockquote><pre>
8.1978 + * str.substring(begin, end)</pre></blockquote>
8.1979 + *
8.1980 + * This method is defined so that the <tt>String</tt> class can implement
8.1981 + * the {@link CharSequence} interface. </p>
8.1982 + *
8.1983 + * @param beginIndex the begin index, inclusive.
8.1984 + * @param endIndex the end index, exclusive.
8.1985 + * @return the specified subsequence.
8.1986 + *
8.1987 + * @throws IndexOutOfBoundsException
8.1988 + * if <tt>beginIndex</tt> or <tt>endIndex</tt> are negative,
8.1989 + * if <tt>endIndex</tt> is greater than <tt>length()</tt>,
8.1990 + * or if <tt>beginIndex</tt> is greater than <tt>startIndex</tt>
8.1991 + *
8.1992 + * @since 1.4
8.1993 + * @spec JSR-51
8.1994 + */
8.1995 + public CharSequence subSequence(int beginIndex, int endIndex) {
8.1996 + return this.substring(beginIndex, endIndex);
8.1997 + }
8.1998 +
8.1999 + /**
8.2000 + * Concatenates the specified string to the end of this string.
8.2001 + * <p>
8.2002 + * If the length of the argument string is <code>0</code>, then this
8.2003 + * <code>String</code> object is returned. Otherwise, a new
8.2004 + * <code>String</code> object is created, representing a character
8.2005 + * sequence that is the concatenation of the character sequence
8.2006 + * represented by this <code>String</code> object and the character
8.2007 + * sequence represented by the argument string.<p>
8.2008 + * Examples:
8.2009 + * <blockquote><pre>
8.2010 + * "cares".concat("s") returns "caress"
8.2011 + * "to".concat("get").concat("her") returns "together"
8.2012 + * </pre></blockquote>
8.2013 + *
8.2014 + * @param str the <code>String</code> that is concatenated to the end
8.2015 + * of this <code>String</code>.
8.2016 + * @return a string that represents the concatenation of this object's
8.2017 + * characters followed by the string argument's characters.
8.2018 + */
8.2019 + public String concat(String str) {
8.2020 + int otherLen = str.length();
8.2021 + if (otherLen == 0) {
8.2022 + return this;
8.2023 + }
8.2024 + char buf[] = new char[count + otherLen];
8.2025 + getChars(0, count, buf, 0);
8.2026 + str.getChars(0, otherLen, buf, count);
8.2027 + return new String(0, count + otherLen, buf);
8.2028 + }
8.2029 +
8.2030 + /**
8.2031 + * Returns a new string resulting from replacing all occurrences of
8.2032 + * <code>oldChar</code> in this string with <code>newChar</code>.
8.2033 + * <p>
8.2034 + * If the character <code>oldChar</code> does not occur in the
8.2035 + * character sequence represented by this <code>String</code> object,
8.2036 + * then a reference to this <code>String</code> object is returned.
8.2037 + * Otherwise, a new <code>String</code> object is created that
8.2038 + * represents a character sequence identical to the character sequence
8.2039 + * represented by this <code>String</code> object, except that every
8.2040 + * occurrence of <code>oldChar</code> is replaced by an occurrence
8.2041 + * of <code>newChar</code>.
8.2042 + * <p>
8.2043 + * Examples:
8.2044 + * <blockquote><pre>
8.2045 + * "mesquite in your cellar".replace('e', 'o')
8.2046 + * returns "mosquito in your collar"
8.2047 + * "the war of baronets".replace('r', 'y')
8.2048 + * returns "the way of bayonets"
8.2049 + * "sparring with a purple porpoise".replace('p', 't')
8.2050 + * returns "starring with a turtle tortoise"
8.2051 + * "JonL".replace('q', 'x') returns "JonL" (no change)
8.2052 + * </pre></blockquote>
8.2053 + *
8.2054 + * @param oldChar the old character.
8.2055 + * @param newChar the new character.
8.2056 + * @return a string derived from this string by replacing every
8.2057 + * occurrence of <code>oldChar</code> with <code>newChar</code>.
8.2058 + */
8.2059 + public String replace(char oldChar, char newChar) {
8.2060 + if (oldChar != newChar) {
8.2061 + int len = count;
8.2062 + int i = -1;
8.2063 + char[] val = value; /* avoid getfield opcode */
8.2064 + int off = offset; /* avoid getfield opcode */
8.2065 +
8.2066 + while (++i < len) {
8.2067 + if (val[off + i] == oldChar) {
8.2068 + break;
8.2069 + }
8.2070 + }
8.2071 + if (i < len) {
8.2072 + char buf[] = new char[len];
8.2073 + for (int j = 0 ; j < i ; j++) {
8.2074 + buf[j] = val[off+j];
8.2075 + }
8.2076 + while (i < len) {
8.2077 + char c = val[off + i];
8.2078 + buf[i] = (c == oldChar) ? newChar : c;
8.2079 + i++;
8.2080 + }
8.2081 + return new String(0, len, buf);
8.2082 + }
8.2083 + }
8.2084 + return this;
8.2085 + }
8.2086 +
8.2087 + /**
8.2088 + * Tells whether or not this string matches the given <a
8.2089 + * href="../util/regex/Pattern.html#sum">regular expression</a>.
8.2090 + *
8.2091 + * <p> An invocation of this method of the form
8.2092 + * <i>str</i><tt>.matches(</tt><i>regex</i><tt>)</tt> yields exactly the
8.2093 + * same result as the expression
8.2094 + *
8.2095 + * <blockquote><tt> {@link java.util.regex.Pattern}.{@link
8.2096 + * java.util.regex.Pattern#matches(String,CharSequence)
8.2097 + * matches}(</tt><i>regex</i><tt>,</tt> <i>str</i><tt>)</tt></blockquote>
8.2098 + *
8.2099 + * @param regex
8.2100 + * the regular expression to which this string is to be matched
8.2101 + *
8.2102 + * @return <tt>true</tt> if, and only if, this string matches the
8.2103 + * given regular expression
8.2104 + *
8.2105 + * @throws PatternSyntaxException
8.2106 + * if the regular expression's syntax is invalid
8.2107 + *
8.2108 + * @see java.util.regex.Pattern
8.2109 + *
8.2110 + * @since 1.4
8.2111 + * @spec JSR-51
8.2112 + */
8.2113 + public boolean matches(String regex) {
8.2114 + return Pattern.matches(regex, this);
8.2115 + }
8.2116 +
8.2117 + /**
8.2118 + * Returns true if and only if this string contains the specified
8.2119 + * sequence of char values.
8.2120 + *
8.2121 + * @param s the sequence to search for
8.2122 + * @return true if this string contains <code>s</code>, false otherwise
8.2123 + * @throws NullPointerException if <code>s</code> is <code>null</code>
8.2124 + * @since 1.5
8.2125 + */
8.2126 + public boolean contains(CharSequence s) {
8.2127 + return indexOf(s.toString()) > -1;
8.2128 + }
8.2129 +
8.2130 + /**
8.2131 + * Replaces the first substring of this string that matches the given <a
8.2132 + * href="../util/regex/Pattern.html#sum">regular expression</a> with the
8.2133 + * given replacement.
8.2134 + *
8.2135 + * <p> An invocation of this method of the form
8.2136 + * <i>str</i><tt>.replaceFirst(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
8.2137 + * yields exactly the same result as the expression
8.2138 + *
8.2139 + * <blockquote><tt>
8.2140 + * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
8.2141 + * compile}(</tt><i>regex</i><tt>).{@link
8.2142 + * java.util.regex.Pattern#matcher(java.lang.CharSequence)
8.2143 + * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceFirst
8.2144 + * replaceFirst}(</tt><i>repl</i><tt>)</tt></blockquote>
8.2145 + *
8.2146 + *<p>
8.2147 + * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
8.2148 + * replacement string may cause the results to be different than if it were
8.2149 + * being treated as a literal replacement string; see
8.2150 + * {@link java.util.regex.Matcher#replaceFirst}.
8.2151 + * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
8.2152 + * meaning of these characters, if desired.
8.2153 + *
8.2154 + * @param regex
8.2155 + * the regular expression to which this string is to be matched
8.2156 + * @param replacement
8.2157 + * the string to be substituted for the first match
8.2158 + *
8.2159 + * @return The resulting <tt>String</tt>
8.2160 + *
8.2161 + * @throws PatternSyntaxException
8.2162 + * if the regular expression's syntax is invalid
8.2163 + *
8.2164 + * @see java.util.regex.Pattern
8.2165 + *
8.2166 + * @since 1.4
8.2167 + * @spec JSR-51
8.2168 + */
8.2169 + public String replaceFirst(String regex, String replacement) {
8.2170 + return Pattern.compile(regex).matcher(this).replaceFirst(replacement);
8.2171 + }
8.2172 +
8.2173 + /**
8.2174 + * Replaces each substring of this string that matches the given <a
8.2175 + * href="../util/regex/Pattern.html#sum">regular expression</a> with the
8.2176 + * given replacement.
8.2177 + *
8.2178 + * <p> An invocation of this method of the form
8.2179 + * <i>str</i><tt>.replaceAll(</tt><i>regex</i><tt>,</tt> <i>repl</i><tt>)</tt>
8.2180 + * yields exactly the same result as the expression
8.2181 + *
8.2182 + * <blockquote><tt>
8.2183 + * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
8.2184 + * compile}(</tt><i>regex</i><tt>).{@link
8.2185 + * java.util.regex.Pattern#matcher(java.lang.CharSequence)
8.2186 + * matcher}(</tt><i>str</i><tt>).{@link java.util.regex.Matcher#replaceAll
8.2187 + * replaceAll}(</tt><i>repl</i><tt>)</tt></blockquote>
8.2188 + *
8.2189 + *<p>
8.2190 + * Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in the
8.2191 + * replacement string may cause the results to be different than if it were
8.2192 + * being treated as a literal replacement string; see
8.2193 + * {@link java.util.regex.Matcher#replaceAll Matcher.replaceAll}.
8.2194 + * Use {@link java.util.regex.Matcher#quoteReplacement} to suppress the special
8.2195 + * meaning of these characters, if desired.
8.2196 + *
8.2197 + * @param regex
8.2198 + * the regular expression to which this string is to be matched
8.2199 + * @param replacement
8.2200 + * the string to be substituted for each match
8.2201 + *
8.2202 + * @return The resulting <tt>String</tt>
8.2203 + *
8.2204 + * @throws PatternSyntaxException
8.2205 + * if the regular expression's syntax is invalid
8.2206 + *
8.2207 + * @see java.util.regex.Pattern
8.2208 + *
8.2209 + * @since 1.4
8.2210 + * @spec JSR-51
8.2211 + */
8.2212 + public String replaceAll(String regex, String replacement) {
8.2213 + return Pattern.compile(regex).matcher(this).replaceAll(replacement);
8.2214 + }
8.2215 +
8.2216 + /**
8.2217 + * Replaces each substring of this string that matches the literal target
8.2218 + * sequence with the specified literal replacement sequence. The
8.2219 + * replacement proceeds from the beginning of the string to the end, for
8.2220 + * example, replacing "aa" with "b" in the string "aaa" will result in
8.2221 + * "ba" rather than "ab".
8.2222 + *
8.2223 + * @param target The sequence of char values to be replaced
8.2224 + * @param replacement The replacement sequence of char values
8.2225 + * @return The resulting string
8.2226 + * @throws NullPointerException if <code>target</code> or
8.2227 + * <code>replacement</code> is <code>null</code>.
8.2228 + * @since 1.5
8.2229 + */
8.2230 + public String replace(CharSequence target, CharSequence replacement) {
8.2231 + return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
8.2232 + this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
8.2233 + }
8.2234 +
8.2235 + /**
8.2236 + * Splits this string around matches of the given
8.2237 + * <a href="../util/regex/Pattern.html#sum">regular expression</a>.
8.2238 + *
8.2239 + * <p> The array returned by this method contains each substring of this
8.2240 + * string that is terminated by another substring that matches the given
8.2241 + * expression or is terminated by the end of the string. The substrings in
8.2242 + * the array are in the order in which they occur in this string. If the
8.2243 + * expression does not match any part of the input then the resulting array
8.2244 + * has just one element, namely this string.
8.2245 + *
8.2246 + * <p> The <tt>limit</tt> parameter controls the number of times the
8.2247 + * pattern is applied and therefore affects the length of the resulting
8.2248 + * array. If the limit <i>n</i> is greater than zero then the pattern
8.2249 + * will be applied at most <i>n</i> - 1 times, the array's
8.2250 + * length will be no greater than <i>n</i>, and the array's last entry
8.2251 + * will contain all input beyond the last matched delimiter. If <i>n</i>
8.2252 + * is non-positive then the pattern will be applied as many times as
8.2253 + * possible and the array can have any length. If <i>n</i> is zero then
8.2254 + * the pattern will be applied as many times as possible, the array can
8.2255 + * have any length, and trailing empty strings will be discarded.
8.2256 + *
8.2257 + * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the
8.2258 + * following results with these parameters:
8.2259 + *
8.2260 + * <blockquote><table cellpadding=1 cellspacing=0 summary="Split example showing regex, limit, and result">
8.2261 + * <tr>
8.2262 + * <th>Regex</th>
8.2263 + * <th>Limit</th>
8.2264 + * <th>Result</th>
8.2265 + * </tr>
8.2266 + * <tr><td align=center>:</td>
8.2267 + * <td align=center>2</td>
8.2268 + * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
8.2269 + * <tr><td align=center>:</td>
8.2270 + * <td align=center>5</td>
8.2271 + * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
8.2272 + * <tr><td align=center>:</td>
8.2273 + * <td align=center>-2</td>
8.2274 + * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
8.2275 + * <tr><td align=center>o</td>
8.2276 + * <td align=center>5</td>
8.2277 + * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
8.2278 + * <tr><td align=center>o</td>
8.2279 + * <td align=center>-2</td>
8.2280 + * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
8.2281 + * <tr><td align=center>o</td>
8.2282 + * <td align=center>0</td>
8.2283 + * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
8.2284 + * </table></blockquote>
8.2285 + *
8.2286 + * <p> An invocation of this method of the form
8.2287 + * <i>str.</i><tt>split(</tt><i>regex</i><tt>,</tt> <i>n</i><tt>)</tt>
8.2288 + * yields the same result as the expression
8.2289 + *
8.2290 + * <blockquote>
8.2291 + * {@link java.util.regex.Pattern}.{@link java.util.regex.Pattern#compile
8.2292 + * compile}<tt>(</tt><i>regex</i><tt>)</tt>.{@link
8.2293 + * java.util.regex.Pattern#split(java.lang.CharSequence,int)
8.2294 + * split}<tt>(</tt><i>str</i><tt>,</tt> <i>n</i><tt>)</tt>
8.2295 + * </blockquote>
8.2296 + *
8.2297 + *
8.2298 + * @param regex
8.2299 + * the delimiting regular expression
8.2300 + *
8.2301 + * @param limit
8.2302 + * the result threshold, as described above
8.2303 + *
8.2304 + * @return the array of strings computed by splitting this string
8.2305 + * around matches of the given regular expression
8.2306 + *
8.2307 + * @throws PatternSyntaxException
8.2308 + * if the regular expression's syntax is invalid
8.2309 + *
8.2310 + * @see java.util.regex.Pattern
8.2311 + *
8.2312 + * @since 1.4
8.2313 + * @spec JSR-51
8.2314 + */
8.2315 + public String[] split(String regex, int limit) {
8.2316 + /* fastpath if the regex is a
8.2317 + (1)one-char String and this character is not one of the
8.2318 + RegEx's meta characters ".$|()[{^?*+\\", or
8.2319 + (2)two-char String and the first char is the backslash and
8.2320 + the second is not the ascii digit or ascii letter.
8.2321 + */
8.2322 + char ch = 0;
8.2323 + if (((regex.count == 1 &&
8.2324 + ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
8.2325 + (regex.length() == 2 &&
8.2326 + regex.charAt(0) == '\\' &&
8.2327 + (((ch = regex.charAt(1))-'0')|('9'-ch)) < 0 &&
8.2328 + ((ch-'a')|('z'-ch)) < 0 &&
8.2329 + ((ch-'A')|('Z'-ch)) < 0)) &&
8.2330 + (ch < Character.MIN_HIGH_SURROGATE ||
8.2331 + ch > Character.MAX_LOW_SURROGATE))
8.2332 + {
8.2333 + int off = 0;
8.2334 + int next = 0;
8.2335 + boolean limited = limit > 0;
8.2336 + ArrayList<String> list = new ArrayList<>();
8.2337 + while ((next = indexOf(ch, off)) != -1) {
8.2338 + if (!limited || list.size() < limit - 1) {
8.2339 + list.add(substring(off, next));
8.2340 + off = next + 1;
8.2341 + } else { // last one
8.2342 + //assert (list.size() == limit - 1);
8.2343 + list.add(substring(off, count));
8.2344 + off = count;
8.2345 + break;
8.2346 + }
8.2347 + }
8.2348 + // If no match was found, return this
8.2349 + if (off == 0)
8.2350 + return new String[] { this };
8.2351 +
8.2352 + // Add remaining segment
8.2353 + if (!limited || list.size() < limit)
8.2354 + list.add(substring(off, count));
8.2355 +
8.2356 + // Construct result
8.2357 + int resultSize = list.size();
8.2358 + if (limit == 0)
8.2359 + while (resultSize > 0 && list.get(resultSize-1).length() == 0)
8.2360 + resultSize--;
8.2361 + String[] result = new String[resultSize];
8.2362 + return list.subList(0, resultSize).toArray(result);
8.2363 + }
8.2364 + return Pattern.compile(regex).split(this, limit);
8.2365 + }
8.2366 +
8.2367 + /**
8.2368 + * Splits this string around matches of the given <a
8.2369 + * href="../util/regex/Pattern.html#sum">regular expression</a>.
8.2370 + *
8.2371 + * <p> This method works as if by invoking the two-argument {@link
8.2372 + * #split(String, int) split} method with the given expression and a limit
8.2373 + * argument of zero. Trailing empty strings are therefore not included in
8.2374 + * the resulting array.
8.2375 + *
8.2376 + * <p> The string <tt>"boo:and:foo"</tt>, for example, yields the following
8.2377 + * results with these expressions:
8.2378 + *
8.2379 + * <blockquote><table cellpadding=1 cellspacing=0 summary="Split examples showing regex and result">
8.2380 + * <tr>
8.2381 + * <th>Regex</th>
8.2382 + * <th>Result</th>
8.2383 + * </tr>
8.2384 + * <tr><td align=center>:</td>
8.2385 + * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
8.2386 + * <tr><td align=center>o</td>
8.2387 + * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
8.2388 + * </table></blockquote>
8.2389 + *
8.2390 + *
8.2391 + * @param regex
8.2392 + * the delimiting regular expression
8.2393 + *
8.2394 + * @return the array of strings computed by splitting this string
8.2395 + * around matches of the given regular expression
8.2396 + *
8.2397 + * @throws PatternSyntaxException
8.2398 + * if the regular expression's syntax is invalid
8.2399 + *
8.2400 + * @see java.util.regex.Pattern
8.2401 + *
8.2402 + * @since 1.4
8.2403 + * @spec JSR-51
8.2404 + */
8.2405 + public String[] split(String regex) {
8.2406 + return split(regex, 0);
8.2407 + }
8.2408 +
8.2409 + /**
8.2410 + * Converts all of the characters in this <code>String</code> to lower
8.2411 + * case using the rules of the given <code>Locale</code>. Case mapping is based
8.2412 + * on the Unicode Standard version specified by the {@link java.lang.Character Character}
8.2413 + * class. Since case mappings are not always 1:1 char mappings, the resulting
8.2414 + * <code>String</code> may be a different length than the original <code>String</code>.
8.2415 + * <p>
8.2416 + * Examples of lowercase mappings are in the following table:
8.2417 + * <table border="1" summary="Lowercase mapping examples showing language code of locale, upper case, lower case, and description">
8.2418 + * <tr>
8.2419 + * <th>Language Code of Locale</th>
8.2420 + * <th>Upper Case</th>
8.2421 + * <th>Lower Case</th>
8.2422 + * <th>Description</th>
8.2423 + * </tr>
8.2424 + * <tr>
8.2425 + * <td>tr (Turkish)</td>
8.2426 + * <td>\u0130</td>
8.2427 + * <td>\u0069</td>
8.2428 + * <td>capital letter I with dot above -> small letter i</td>
8.2429 + * </tr>
8.2430 + * <tr>
8.2431 + * <td>tr (Turkish)</td>
8.2432 + * <td>\u0049</td>
8.2433 + * <td>\u0131</td>
8.2434 + * <td>capital letter I -> small letter dotless i </td>
8.2435 + * </tr>
8.2436 + * <tr>
8.2437 + * <td>(all)</td>
8.2438 + * <td>French Fries</td>
8.2439 + * <td>french fries</td>
8.2440 + * <td>lowercased all chars in String</td>
8.2441 + * </tr>
8.2442 + * <tr>
8.2443 + * <td>(all)</td>
8.2444 + * <td><img src="doc-files/capiota.gif" alt="capiota"><img src="doc-files/capchi.gif" alt="capchi">
8.2445 + * <img src="doc-files/captheta.gif" alt="captheta"><img src="doc-files/capupsil.gif" alt="capupsil">
8.2446 + * <img src="doc-files/capsigma.gif" alt="capsigma"></td>
8.2447 + * <td><img src="doc-files/iota.gif" alt="iota"><img src="doc-files/chi.gif" alt="chi">
8.2448 + * <img src="doc-files/theta.gif" alt="theta"><img src="doc-files/upsilon.gif" alt="upsilon">
8.2449 + * <img src="doc-files/sigma1.gif" alt="sigma"></td>
8.2450 + * <td>lowercased all chars in String</td>
8.2451 + * </tr>
8.2452 + * </table>
8.2453 + *
8.2454 + * @param locale use the case transformation rules for this locale
8.2455 + * @return the <code>String</code>, converted to lowercase.
8.2456 + * @see java.lang.String#toLowerCase()
8.2457 + * @see java.lang.String#toUpperCase()
8.2458 + * @see java.lang.String#toUpperCase(Locale)
8.2459 + * @since 1.1
8.2460 + */
8.2461 + public String toLowerCase(Locale locale) {
8.2462 + if (locale == null) {
8.2463 + throw new NullPointerException();
8.2464 + }
8.2465 +
8.2466 + int firstUpper;
8.2467 +
8.2468 + /* Now check if there are any characters that need to be changed. */
8.2469 + scan: {
8.2470 + for (firstUpper = 0 ; firstUpper < count; ) {
8.2471 + char c = value[offset+firstUpper];
8.2472 + if ((c >= Character.MIN_HIGH_SURROGATE) &&
8.2473 + (c <= Character.MAX_HIGH_SURROGATE)) {
8.2474 + int supplChar = codePointAt(firstUpper);
8.2475 + if (supplChar != Character.toLowerCase(supplChar)) {
8.2476 + break scan;
8.2477 + }
8.2478 + firstUpper += Character.charCount(supplChar);
8.2479 + } else {
8.2480 + if (c != Character.toLowerCase(c)) {
8.2481 + break scan;
8.2482 + }
8.2483 + firstUpper++;
8.2484 + }
8.2485 + }
8.2486 + return this;
8.2487 + }
8.2488 +
8.2489 + char[] result = new char[count];
8.2490 + int resultOffset = 0; /* result may grow, so i+resultOffset
8.2491 + * is the write location in result */
8.2492 +
8.2493 + /* Just copy the first few lowerCase characters. */
8.2494 + System.arraycopy(value, offset, result, 0, firstUpper);
8.2495 +
8.2496 + String lang = locale.getLanguage();
8.2497 + boolean localeDependent =
8.2498 + (lang == "tr" || lang == "az" || lang == "lt");
8.2499 + char[] lowerCharArray;
8.2500 + int lowerChar;
8.2501 + int srcChar;
8.2502 + int srcCount;
8.2503 + for (int i = firstUpper; i < count; i += srcCount) {
8.2504 + srcChar = (int)value[offset+i];
8.2505 + if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
8.2506 + (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
8.2507 + srcChar = codePointAt(i);
8.2508 + srcCount = Character.charCount(srcChar);
8.2509 + } else {
8.2510 + srcCount = 1;
8.2511 + }
8.2512 + if (localeDependent || srcChar == '\u03A3') { // GREEK CAPITAL LETTER SIGMA
8.2513 + lowerChar = ConditionalSpecialCasing.toLowerCaseEx(this, i, locale);
8.2514 + } else if (srcChar == '\u0130') { // LATIN CAPITAL LETTER I DOT
8.2515 + lowerChar = Character.ERROR;
8.2516 + } else {
8.2517 + lowerChar = Character.toLowerCase(srcChar);
8.2518 + }
8.2519 + if ((lowerChar == Character.ERROR) ||
8.2520 + (lowerChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
8.2521 + if (lowerChar == Character.ERROR) {
8.2522 + if (!localeDependent && srcChar == '\u0130') {
8.2523 + lowerCharArray =
8.2524 + ConditionalSpecialCasing.toLowerCaseCharArray(this, i, Locale.ENGLISH);
8.2525 + } else {
8.2526 + lowerCharArray =
8.2527 + ConditionalSpecialCasing.toLowerCaseCharArray(this, i, locale);
8.2528 + }
8.2529 + } else if (srcCount == 2) {
8.2530 + resultOffset += Character.toChars(lowerChar, result, i + resultOffset) - srcCount;
8.2531 + continue;
8.2532 + } else {
8.2533 + lowerCharArray = Character.toChars(lowerChar);
8.2534 + }
8.2535 +
8.2536 + /* Grow result if needed */
8.2537 + int mapLen = lowerCharArray.length;
8.2538 + if (mapLen > srcCount) {
8.2539 + char[] result2 = new char[result.length + mapLen - srcCount];
8.2540 + System.arraycopy(result, 0, result2, 0,
8.2541 + i + resultOffset);
8.2542 + result = result2;
8.2543 + }
8.2544 + for (int x=0; x<mapLen; ++x) {
8.2545 + result[i+resultOffset+x] = lowerCharArray[x];
8.2546 + }
8.2547 + resultOffset += (mapLen - srcCount);
8.2548 + } else {
8.2549 + result[i+resultOffset] = (char)lowerChar;
8.2550 + }
8.2551 + }
8.2552 + return new String(0, count+resultOffset, result);
8.2553 + }
8.2554 +
8.2555 + /**
8.2556 + * Converts all of the characters in this <code>String</code> to lower
8.2557 + * case using the rules of the default locale. This is equivalent to calling
8.2558 + * <code>toLowerCase(Locale.getDefault())</code>.
8.2559 + * <p>
8.2560 + * <b>Note:</b> This method is locale sensitive, and may produce unexpected
8.2561 + * results if used for strings that are intended to be interpreted locale
8.2562 + * independently.
8.2563 + * Examples are programming language identifiers, protocol keys, and HTML
8.2564 + * tags.
8.2565 + * For instance, <code>"TITLE".toLowerCase()</code> in a Turkish locale
8.2566 + * returns <code>"t\u005Cu0131tle"</code>, where '\u005Cu0131' is the
8.2567 + * LATIN SMALL LETTER DOTLESS I character.
8.2568 + * To obtain correct results for locale insensitive strings, use
8.2569 + * <code>toLowerCase(Locale.ENGLISH)</code>.
8.2570 + * <p>
8.2571 + * @return the <code>String</code>, converted to lowercase.
8.2572 + * @see java.lang.String#toLowerCase(Locale)
8.2573 + */
8.2574 + public String toLowerCase() {
8.2575 + return toLowerCase(Locale.getDefault());
8.2576 + }
8.2577 +
8.2578 + /**
8.2579 + * Converts all of the characters in this <code>String</code> to upper
8.2580 + * case using the rules of the given <code>Locale</code>. Case mapping is based
8.2581 + * on the Unicode Standard version specified by the {@link java.lang.Character Character}
8.2582 + * class. Since case mappings are not always 1:1 char mappings, the resulting
8.2583 + * <code>String</code> may be a different length than the original <code>String</code>.
8.2584 + * <p>
8.2585 + * Examples of locale-sensitive and 1:M case mappings are in the following table.
8.2586 + * <p>
8.2587 + * <table border="1" summary="Examples of locale-sensitive and 1:M case mappings. Shows Language code of locale, lower case, upper case, and description.">
8.2588 + * <tr>
8.2589 + * <th>Language Code of Locale</th>
8.2590 + * <th>Lower Case</th>
8.2591 + * <th>Upper Case</th>
8.2592 + * <th>Description</th>
8.2593 + * </tr>
8.2594 + * <tr>
8.2595 + * <td>tr (Turkish)</td>
8.2596 + * <td>\u0069</td>
8.2597 + * <td>\u0130</td>
8.2598 + * <td>small letter i -> capital letter I with dot above</td>
8.2599 + * </tr>
8.2600 + * <tr>
8.2601 + * <td>tr (Turkish)</td>
8.2602 + * <td>\u0131</td>
8.2603 + * <td>\u0049</td>
8.2604 + * <td>small letter dotless i -> capital letter I</td>
8.2605 + * </tr>
8.2606 + * <tr>
8.2607 + * <td>(all)</td>
8.2608 + * <td>\u00df</td>
8.2609 + * <td>\u0053 \u0053</td>
8.2610 + * <td>small letter sharp s -> two letters: SS</td>
8.2611 + * </tr>
8.2612 + * <tr>
8.2613 + * <td>(all)</td>
8.2614 + * <td>Fahrvergnügen</td>
8.2615 + * <td>FAHRVERGNÜGEN</td>
8.2616 + * <td></td>
8.2617 + * </tr>
8.2618 + * </table>
8.2619 + * @param locale use the case transformation rules for this locale
8.2620 + * @return the <code>String</code>, converted to uppercase.
8.2621 + * @see java.lang.String#toUpperCase()
8.2622 + * @see java.lang.String#toLowerCase()
8.2623 + * @see java.lang.String#toLowerCase(Locale)
8.2624 + * @since 1.1
8.2625 + */
8.2626 + public String toUpperCase(Locale locale) {
8.2627 + if (locale == null) {
8.2628 + throw new NullPointerException();
8.2629 + }
8.2630 +
8.2631 + int firstLower;
8.2632 +
8.2633 + /* Now check if there are any characters that need to be changed. */
8.2634 + scan: {
8.2635 + for (firstLower = 0 ; firstLower < count; ) {
8.2636 + int c = (int)value[offset+firstLower];
8.2637 + int srcCount;
8.2638 + if ((c >= Character.MIN_HIGH_SURROGATE) &&
8.2639 + (c <= Character.MAX_HIGH_SURROGATE)) {
8.2640 + c = codePointAt(firstLower);
8.2641 + srcCount = Character.charCount(c);
8.2642 + } else {
8.2643 + srcCount = 1;
8.2644 + }
8.2645 + int upperCaseChar = Character.toUpperCaseEx(c);
8.2646 + if ((upperCaseChar == Character.ERROR) ||
8.2647 + (c != upperCaseChar)) {
8.2648 + break scan;
8.2649 + }
8.2650 + firstLower += srcCount;
8.2651 + }
8.2652 + return this;
8.2653 + }
8.2654 +
8.2655 + char[] result = new char[count]; /* may grow */
8.2656 + int resultOffset = 0; /* result may grow, so i+resultOffset
8.2657 + * is the write location in result */
8.2658 +
8.2659 + /* Just copy the first few upperCase characters. */
8.2660 + System.arraycopy(value, offset, result, 0, firstLower);
8.2661 +
8.2662 + String lang = locale.getLanguage();
8.2663 + boolean localeDependent =
8.2664 + (lang == "tr" || lang == "az" || lang == "lt");
8.2665 + char[] upperCharArray;
8.2666 + int upperChar;
8.2667 + int srcChar;
8.2668 + int srcCount;
8.2669 + for (int i = firstLower; i < count; i += srcCount) {
8.2670 + srcChar = (int)value[offset+i];
8.2671 + if ((char)srcChar >= Character.MIN_HIGH_SURROGATE &&
8.2672 + (char)srcChar <= Character.MAX_HIGH_SURROGATE) {
8.2673 + srcChar = codePointAt(i);
8.2674 + srcCount = Character.charCount(srcChar);
8.2675 + } else {
8.2676 + srcCount = 1;
8.2677 + }
8.2678 + if (localeDependent) {
8.2679 + upperChar = ConditionalSpecialCasing.toUpperCaseEx(this, i, locale);
8.2680 + } else {
8.2681 + upperChar = Character.toUpperCaseEx(srcChar);
8.2682 + }
8.2683 + if ((upperChar == Character.ERROR) ||
8.2684 + (upperChar >= Character.MIN_SUPPLEMENTARY_CODE_POINT)) {
8.2685 + if (upperChar == Character.ERROR) {
8.2686 + if (localeDependent) {
8.2687 + upperCharArray =
8.2688 + ConditionalSpecialCasing.toUpperCaseCharArray(this, i, locale);
8.2689 + } else {
8.2690 + upperCharArray = Character.toUpperCaseCharArray(srcChar);
8.2691 + }
8.2692 + } else if (srcCount == 2) {
8.2693 + resultOffset += Character.toChars(upperChar, result, i + resultOffset) - srcCount;
8.2694 + continue;
8.2695 + } else {
8.2696 + upperCharArray = Character.toChars(upperChar);
8.2697 + }
8.2698 +
8.2699 + /* Grow result if needed */
8.2700 + int mapLen = upperCharArray.length;
8.2701 + if (mapLen > srcCount) {
8.2702 + char[] result2 = new char[result.length + mapLen - srcCount];
8.2703 + System.arraycopy(result, 0, result2, 0,
8.2704 + i + resultOffset);
8.2705 + result = result2;
8.2706 + }
8.2707 + for (int x=0; x<mapLen; ++x) {
8.2708 + result[i+resultOffset+x] = upperCharArray[x];
8.2709 + }
8.2710 + resultOffset += (mapLen - srcCount);
8.2711 + } else {
8.2712 + result[i+resultOffset] = (char)upperChar;
8.2713 + }
8.2714 + }
8.2715 + return new String(0, count+resultOffset, result);
8.2716 + }
8.2717 +
8.2718 + /**
8.2719 + * Converts all of the characters in this <code>String</code> to upper
8.2720 + * case using the rules of the default locale. This method is equivalent to
8.2721 + * <code>toUpperCase(Locale.getDefault())</code>.
8.2722 + * <p>
8.2723 + * <b>Note:</b> This method is locale sensitive, and may produce unexpected
8.2724 + * results if used for strings that are intended to be interpreted locale
8.2725 + * independently.
8.2726 + * Examples are programming language identifiers, protocol keys, and HTML
8.2727 + * tags.
8.2728 + * For instance, <code>"title".toUpperCase()</code> in a Turkish locale
8.2729 + * returns <code>"T\u005Cu0130TLE"</code>, where '\u005Cu0130' is the
8.2730 + * LATIN CAPITAL LETTER I WITH DOT ABOVE character.
8.2731 + * To obtain correct results for locale insensitive strings, use
8.2732 + * <code>toUpperCase(Locale.ENGLISH)</code>.
8.2733 + * <p>
8.2734 + * @return the <code>String</code>, converted to uppercase.
8.2735 + * @see java.lang.String#toUpperCase(Locale)
8.2736 + */
8.2737 + public String toUpperCase() {
8.2738 + return toUpperCase(Locale.getDefault());
8.2739 + }
8.2740 +
8.2741 + /**
8.2742 + * Returns a copy of the string, with leading and trailing whitespace
8.2743 + * omitted.
8.2744 + * <p>
8.2745 + * If this <code>String</code> object represents an empty character
8.2746 + * sequence, or the first and last characters of character sequence
8.2747 + * represented by this <code>String</code> object both have codes
8.2748 + * greater than <code>'\u0020'</code> (the space character), then a
8.2749 + * reference to this <code>String</code> object is returned.
8.2750 + * <p>
8.2751 + * Otherwise, if there is no character with a code greater than
8.2752 + * <code>'\u0020'</code> in the string, then a new
8.2753 + * <code>String</code> object representing an empty string is created
8.2754 + * and returned.
8.2755 + * <p>
8.2756 + * Otherwise, let <i>k</i> be the index of the first character in the
8.2757 + * string whose code is greater than <code>'\u0020'</code>, and let
8.2758 + * <i>m</i> be the index of the last character in the string whose code
8.2759 + * is greater than <code>'\u0020'</code>. A new <code>String</code>
8.2760 + * object is created, representing the substring of this string that
8.2761 + * begins with the character at index <i>k</i> and ends with the
8.2762 + * character at index <i>m</i>-that is, the result of
8.2763 + * <code>this.substring(<i>k</i>, <i>m</i>+1)</code>.
8.2764 + * <p>
8.2765 + * This method may be used to trim whitespace (as defined above) from
8.2766 + * the beginning and end of a string.
8.2767 + *
8.2768 + * @return A copy of this string with leading and trailing white
8.2769 + * space removed, or this string if it has no leading or
8.2770 + * trailing white space.
8.2771 + */
8.2772 + public String trim() {
8.2773 + int len = count;
8.2774 + int st = 0;
8.2775 + int off = offset; /* avoid getfield opcode */
8.2776 + char[] val = value; /* avoid getfield opcode */
8.2777 +
8.2778 + while ((st < len) && (val[off + st] <= ' ')) {
8.2779 + st++;
8.2780 + }
8.2781 + while ((st < len) && (val[off + len - 1] <= ' ')) {
8.2782 + len--;
8.2783 + }
8.2784 + return ((st > 0) || (len < count)) ? substring(st, len) : this;
8.2785 + }
8.2786 +
8.2787 + /**
8.2788 + * This object (which is already a string!) is itself returned.
8.2789 + *
8.2790 + * @return the string itself.
8.2791 + */
8.2792 + public String toString() {
8.2793 + return this;
8.2794 + }
8.2795 +
8.2796 + /**
8.2797 + * Converts this string to a new character array.
8.2798 + *
8.2799 + * @return a newly allocated character array whose length is the length
8.2800 + * of this string and whose contents are initialized to contain
8.2801 + * the character sequence represented by this string.
8.2802 + */
8.2803 + public char[] toCharArray() {
8.2804 + char result[] = new char[count];
8.2805 + getChars(0, count, result, 0);
8.2806 + return result;
8.2807 + }
8.2808 +
8.2809 + /**
8.2810 + * Returns a formatted string using the specified format string and
8.2811 + * arguments.
8.2812 + *
8.2813 + * <p> The locale always used is the one returned by {@link
8.2814 + * java.util.Locale#getDefault() Locale.getDefault()}.
8.2815 + *
8.2816 + * @param format
8.2817 + * A <a href="../util/Formatter.html#syntax">format string</a>
8.2818 + *
8.2819 + * @param args
8.2820 + * Arguments referenced by the format specifiers in the format
8.2821 + * string. If there are more arguments than format specifiers, the
8.2822 + * extra arguments are ignored. The number of arguments is
8.2823 + * variable and may be zero. The maximum number of arguments is
8.2824 + * limited by the maximum dimension of a Java array as defined by
8.2825 + * <cite>The Java™ Virtual Machine Specification</cite>.
8.2826 + * The behaviour on a
8.2827 + * <tt>null</tt> argument depends on the <a
8.2828 + * href="../util/Formatter.html#syntax">conversion</a>.
8.2829 + *
8.2830 + * @throws IllegalFormatException
8.2831 + * If a format string contains an illegal syntax, a format
8.2832 + * specifier that is incompatible with the given arguments,
8.2833 + * insufficient arguments given the format string, or other
8.2834 + * illegal conditions. For specification of all possible
8.2835 + * formatting errors, see the <a
8.2836 + * href="../util/Formatter.html#detail">Details</a> section of the
8.2837 + * formatter class specification.
8.2838 + *
8.2839 + * @throws NullPointerException
8.2840 + * If the <tt>format</tt> is <tt>null</tt>
8.2841 + *
8.2842 + * @return A formatted string
8.2843 + *
8.2844 + * @see java.util.Formatter
8.2845 + * @since 1.5
8.2846 + */
8.2847 + public static String format(String format, Object ... args) {
8.2848 + return new Formatter().format(format, args).toString();
8.2849 + }
8.2850 +
8.2851 + /**
8.2852 + * Returns a formatted string using the specified locale, format string,
8.2853 + * and arguments.
8.2854 + *
8.2855 + * @param l
8.2856 + * The {@linkplain java.util.Locale locale} to apply during
8.2857 + * formatting. If <tt>l</tt> is <tt>null</tt> then no localization
8.2858 + * is applied.
8.2859 + *
8.2860 + * @param format
8.2861 + * A <a href="../util/Formatter.html#syntax">format string</a>
8.2862 + *
8.2863 + * @param args
8.2864 + * Arguments referenced by the format specifiers in the format
8.2865 + * string. If there are more arguments than format specifiers, the
8.2866 + * extra arguments are ignored. The number of arguments is
8.2867 + * variable and may be zero. The maximum number of arguments is
8.2868 + * limited by the maximum dimension of a Java array as defined by
8.2869 + * <cite>The Java™ Virtual Machine Specification</cite>.
8.2870 + * The behaviour on a
8.2871 + * <tt>null</tt> argument depends on the <a
8.2872 + * href="../util/Formatter.html#syntax">conversion</a>.
8.2873 + *
8.2874 + * @throws IllegalFormatException
8.2875 + * If a format string contains an illegal syntax, a format
8.2876 + * specifier that is incompatible with the given arguments,
8.2877 + * insufficient arguments given the format string, or other
8.2878 + * illegal conditions. For specification of all possible
8.2879 + * formatting errors, see the <a
8.2880 + * href="../util/Formatter.html#detail">Details</a> section of the
8.2881 + * formatter class specification
8.2882 + *
8.2883 + * @throws NullPointerException
8.2884 + * If the <tt>format</tt> is <tt>null</tt>
8.2885 + *
8.2886 + * @return A formatted string
8.2887 + *
8.2888 + * @see java.util.Formatter
8.2889 + * @since 1.5
8.2890 + */
8.2891 + public static String format(Locale l, String format, Object ... args) {
8.2892 + return new Formatter(l).format(format, args).toString();
8.2893 + }
8.2894 +
8.2895 + /**
8.2896 + * Returns the string representation of the <code>Object</code> argument.
8.2897 + *
8.2898 + * @param obj an <code>Object</code>.
8.2899 + * @return if the argument is <code>null</code>, then a string equal to
8.2900 + * <code>"null"</code>; otherwise, the value of
8.2901 + * <code>obj.toString()</code> is returned.
8.2902 + * @see java.lang.Object#toString()
8.2903 + */
8.2904 + public static String valueOf(Object obj) {
8.2905 + return (obj == null) ? "null" : obj.toString();
8.2906 + }
8.2907 +
8.2908 + /**
8.2909 + * Returns the string representation of the <code>char</code> array
8.2910 + * argument. The contents of the character array are copied; subsequent
8.2911 + * modification of the character array does not affect the newly
8.2912 + * created string.
8.2913 + *
8.2914 + * @param data a <code>char</code> array.
8.2915 + * @return a newly allocated string representing the same sequence of
8.2916 + * characters contained in the character array argument.
8.2917 + */
8.2918 + public static String valueOf(char data[]) {
8.2919 + return new String(data);
8.2920 + }
8.2921 +
8.2922 + /**
8.2923 + * Returns the string representation of a specific subarray of the
8.2924 + * <code>char</code> array argument.
8.2925 + * <p>
8.2926 + * The <code>offset</code> argument is the index of the first
8.2927 + * character of the subarray. The <code>count</code> argument
8.2928 + * specifies the length of the subarray. The contents of the subarray
8.2929 + * are copied; subsequent modification of the character array does not
8.2930 + * affect the newly created string.
8.2931 + *
8.2932 + * @param data the character array.
8.2933 + * @param offset the initial offset into the value of the
8.2934 + * <code>String</code>.
8.2935 + * @param count the length of the value of the <code>String</code>.
8.2936 + * @return a string representing the sequence of characters contained
8.2937 + * in the subarray of the character array argument.
8.2938 + * @exception IndexOutOfBoundsException if <code>offset</code> is
8.2939 + * negative, or <code>count</code> is negative, or
8.2940 + * <code>offset+count</code> is larger than
8.2941 + * <code>data.length</code>.
8.2942 + */
8.2943 + public static String valueOf(char data[], int offset, int count) {
8.2944 + return new String(data, offset, count);
8.2945 + }
8.2946 +
8.2947 + /**
8.2948 + * Returns a String that represents the character sequence in the
8.2949 + * array specified.
8.2950 + *
8.2951 + * @param data the character array.
8.2952 + * @param offset initial offset of the subarray.
8.2953 + * @param count length of the subarray.
8.2954 + * @return a <code>String</code> that contains the characters of the
8.2955 + * specified subarray of the character array.
8.2956 + */
8.2957 + public static String copyValueOf(char data[], int offset, int count) {
8.2958 + // All public String constructors now copy the data.
8.2959 + return new String(data, offset, count);
8.2960 + }
8.2961 +
8.2962 + /**
8.2963 + * Returns a String that represents the character sequence in the
8.2964 + * array specified.
8.2965 + *
8.2966 + * @param data the character array.
8.2967 + * @return a <code>String</code> that contains the characters of the
8.2968 + * character array.
8.2969 + */
8.2970 + public static String copyValueOf(char data[]) {
8.2971 + return copyValueOf(data, 0, data.length);
8.2972 + }
8.2973 +
8.2974 + /**
8.2975 + * Returns the string representation of the <code>boolean</code> argument.
8.2976 + *
8.2977 + * @param b a <code>boolean</code>.
8.2978 + * @return if the argument is <code>true</code>, a string equal to
8.2979 + * <code>"true"</code> is returned; otherwise, a string equal to
8.2980 + * <code>"false"</code> is returned.
8.2981 + */
8.2982 + public static String valueOf(boolean b) {
8.2983 + return b ? "true" : "false";
8.2984 + }
8.2985 +
8.2986 + /**
8.2987 + * Returns the string representation of the <code>char</code>
8.2988 + * argument.
8.2989 + *
8.2990 + * @param c a <code>char</code>.
8.2991 + * @return a string of length <code>1</code> containing
8.2992 + * as its single character the argument <code>c</code>.
8.2993 + */
8.2994 + public static String valueOf(char c) {
8.2995 + char data[] = {c};
8.2996 + return new String(0, 1, data);
8.2997 + }
8.2998 +
8.2999 + /**
8.3000 + * Returns the string representation of the <code>int</code> argument.
8.3001 + * <p>
8.3002 + * The representation is exactly the one returned by the
8.3003 + * <code>Integer.toString</code> method of one argument.
8.3004 + *
8.3005 + * @param i an <code>int</code>.
8.3006 + * @return a string representation of the <code>int</code> argument.
8.3007 + * @see java.lang.Integer#toString(int, int)
8.3008 + */
8.3009 + public static String valueOf(int i) {
8.3010 + return Integer.toString(i);
8.3011 + }
8.3012 +
8.3013 + /**
8.3014 + * Returns the string representation of the <code>long</code> argument.
8.3015 + * <p>
8.3016 + * The representation is exactly the one returned by the
8.3017 + * <code>Long.toString</code> method of one argument.
8.3018 + *
8.3019 + * @param l a <code>long</code>.
8.3020 + * @return a string representation of the <code>long</code> argument.
8.3021 + * @see java.lang.Long#toString(long)
8.3022 + */
8.3023 + public static String valueOf(long l) {
8.3024 + return Long.toString(l);
8.3025 + }
8.3026 +
8.3027 + /**
8.3028 + * Returns the string representation of the <code>float</code> argument.
8.3029 + * <p>
8.3030 + * The representation is exactly the one returned by the
8.3031 + * <code>Float.toString</code> method of one argument.
8.3032 + *
8.3033 + * @param f a <code>float</code>.
8.3034 + * @return a string representation of the <code>float</code> argument.
8.3035 + * @see java.lang.Float#toString(float)
8.3036 + */
8.3037 + public static String valueOf(float f) {
8.3038 + return Float.toString(f);
8.3039 + }
8.3040 +
8.3041 + /**
8.3042 + * Returns the string representation of the <code>double</code> argument.
8.3043 + * <p>
8.3044 + * The representation is exactly the one returned by the
8.3045 + * <code>Double.toString</code> method of one argument.
8.3046 + *
8.3047 + * @param d a <code>double</code>.
8.3048 + * @return a string representation of the <code>double</code> argument.
8.3049 + * @see java.lang.Double#toString(double)
8.3050 + */
8.3051 + public static String valueOf(double d) {
8.3052 + return Double.toString(d);
8.3053 + }
8.3054 +
8.3055 + /**
8.3056 + * Returns a canonical representation for the string object.
8.3057 + * <p>
8.3058 + * A pool of strings, initially empty, is maintained privately by the
8.3059 + * class <code>String</code>.
8.3060 + * <p>
8.3061 + * When the intern method is invoked, if the pool already contains a
8.3062 + * string equal to this <code>String</code> object as determined by
8.3063 + * the {@link #equals(Object)} method, then the string from the pool is
8.3064 + * returned. Otherwise, this <code>String</code> object is added to the
8.3065 + * pool and a reference to this <code>String</code> object is returned.
8.3066 + * <p>
8.3067 + * It follows that for any two strings <code>s</code> and <code>t</code>,
8.3068 + * <code>s.intern() == t.intern()</code> is <code>true</code>
8.3069 + * if and only if <code>s.equals(t)</code> is <code>true</code>.
8.3070 + * <p>
8.3071 + * All literal strings and string-valued constant expressions are
8.3072 + * interned. String literals are defined in section 3.10.5 of the
8.3073 + * <cite>The Java™ Language Specification</cite>.
8.3074 + *
8.3075 + * @return a string that has the same contents as this string, but is
8.3076 + * guaranteed to be from a pool of unique strings.
8.3077 + */
8.3078 + public native String intern();
8.3079 +
8.3080 +}
9.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
9.2 +++ b/emul/src/main/java/java/lang/Throwable.java Fri Sep 28 17:59:03 2012 +0200
9.3 @@ -0,0 +1,1080 @@
9.4 +/*
9.5 + * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
9.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
9.7 + *
9.8 + * This code is free software; you can redistribute it and/or modify it
9.9 + * under the terms of the GNU General Public License version 2 only, as
9.10 + * published by the Free Software Foundation. Oracle designates this
9.11 + * particular file as subject to the "Classpath" exception as provided
9.12 + * by Oracle in the LICENSE file that accompanied this code.
9.13 + *
9.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
9.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
9.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
9.17 + * version 2 for more details (a copy is included in the LICENSE file that
9.18 + * accompanied this code).
9.19 + *
9.20 + * You should have received a copy of the GNU General Public License version
9.21 + * 2 along with this work; if not, write to the Free Software Foundation,
9.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
9.23 + *
9.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
9.25 + * or visit www.oracle.com if you need additional information or have any
9.26 + * questions.
9.27 + */
9.28 +
9.29 +package java.lang;
9.30 +import java.io.*;
9.31 +import java.util.*;
9.32 +
9.33 +/**
9.34 + * The {@code Throwable} class is the superclass of all errors and
9.35 + * exceptions in the Java language. Only objects that are instances of this
9.36 + * class (or one of its subclasses) are thrown by the Java Virtual Machine or
9.37 + * can be thrown by the Java {@code throw} statement. Similarly, only
9.38 + * this class or one of its subclasses can be the argument type in a
9.39 + * {@code catch} clause.
9.40 + *
9.41 + * For the purposes of compile-time checking of exceptions, {@code
9.42 + * Throwable} and any subclass of {@code Throwable} that is not also a
9.43 + * subclass of either {@link RuntimeException} or {@link Error} are
9.44 + * regarded as checked exceptions.
9.45 + *
9.46 + * <p>Instances of two subclasses, {@link java.lang.Error} and
9.47 + * {@link java.lang.Exception}, are conventionally used to indicate
9.48 + * that exceptional situations have occurred. Typically, these instances
9.49 + * are freshly created in the context of the exceptional situation so
9.50 + * as to include relevant information (such as stack trace data).
9.51 + *
9.52 + * <p>A throwable contains a snapshot of the execution stack of its
9.53 + * thread at the time it was created. It can also contain a message
9.54 + * string that gives more information about the error. Over time, a
9.55 + * throwable can {@linkplain Throwable#addSuppressed suppress} other
9.56 + * throwables from being propagated. Finally, the throwable can also
9.57 + * contain a <i>cause</i>: another throwable that caused this
9.58 + * throwable to be constructed. The recording of this causal information
9.59 + * is referred to as the <i>chained exception</i> facility, as the
9.60 + * cause can, itself, have a cause, and so on, leading to a "chain" of
9.61 + * exceptions, each caused by another.
9.62 + *
9.63 + * <p>One reason that a throwable may have a cause is that the class that
9.64 + * throws it is built atop a lower layered abstraction, and an operation on
9.65 + * the upper layer fails due to a failure in the lower layer. It would be bad
9.66 + * design to let the throwable thrown by the lower layer propagate outward, as
9.67 + * it is generally unrelated to the abstraction provided by the upper layer.
9.68 + * Further, doing so would tie the API of the upper layer to the details of
9.69 + * its implementation, assuming the lower layer's exception was a checked
9.70 + * exception. Throwing a "wrapped exception" (i.e., an exception containing a
9.71 + * cause) allows the upper layer to communicate the details of the failure to
9.72 + * its caller without incurring either of these shortcomings. It preserves
9.73 + * the flexibility to change the implementation of the upper layer without
9.74 + * changing its API (in particular, the set of exceptions thrown by its
9.75 + * methods).
9.76 + *
9.77 + * <p>A second reason that a throwable may have a cause is that the method
9.78 + * that throws it must conform to a general-purpose interface that does not
9.79 + * permit the method to throw the cause directly. For example, suppose
9.80 + * a persistent collection conforms to the {@link java.util.Collection
9.81 + * Collection} interface, and that its persistence is implemented atop
9.82 + * {@code java.io}. Suppose the internals of the {@code add} method
9.83 + * can throw an {@link java.io.IOException IOException}. The implementation
9.84 + * can communicate the details of the {@code IOException} to its caller
9.85 + * while conforming to the {@code Collection} interface by wrapping the
9.86 + * {@code IOException} in an appropriate unchecked exception. (The
9.87 + * specification for the persistent collection should indicate that it is
9.88 + * capable of throwing such exceptions.)
9.89 + *
9.90 + * <p>A cause can be associated with a throwable in two ways: via a
9.91 + * constructor that takes the cause as an argument, or via the
9.92 + * {@link #initCause(Throwable)} method. New throwable classes that
9.93 + * wish to allow causes to be associated with them should provide constructors
9.94 + * that take a cause and delegate (perhaps indirectly) to one of the
9.95 + * {@code Throwable} constructors that takes a cause.
9.96 + *
9.97 + * Because the {@code initCause} method is public, it allows a cause to be
9.98 + * associated with any throwable, even a "legacy throwable" whose
9.99 + * implementation predates the addition of the exception chaining mechanism to
9.100 + * {@code Throwable}.
9.101 + *
9.102 + * <p>By convention, class {@code Throwable} and its subclasses have two
9.103 + * constructors, one that takes no arguments and one that takes a
9.104 + * {@code String} argument that can be used to produce a detail message.
9.105 + * Further, those subclasses that might likely have a cause associated with
9.106 + * them should have two more constructors, one that takes a
9.107 + * {@code Throwable} (the cause), and one that takes a
9.108 + * {@code String} (the detail message) and a {@code Throwable} (the
9.109 + * cause).
9.110 + *
9.111 + * @author unascribed
9.112 + * @author Josh Bloch (Added exception chaining and programmatic access to
9.113 + * stack trace in 1.4.)
9.114 + * @jls 11.2 Compile-Time Checking of Exceptions
9.115 + * @since JDK1.0
9.116 + */
9.117 +public class Throwable implements Serializable {
9.118 + /** use serialVersionUID from JDK 1.0.2 for interoperability */
9.119 + private static final long serialVersionUID = -3042686055658047285L;
9.120 +
9.121 + /**
9.122 + * Native code saves some indication of the stack backtrace in this slot.
9.123 + */
9.124 + private transient Object backtrace;
9.125 +
9.126 + /**
9.127 + * Specific details about the Throwable. For example, for
9.128 + * {@code FileNotFoundException}, this contains the name of
9.129 + * the file that could not be found.
9.130 + *
9.131 + * @serial
9.132 + */
9.133 + private String detailMessage;
9.134 +
9.135 +
9.136 + /**
9.137 + * Holder class to defer initializing sentinel objects only used
9.138 + * for serialization.
9.139 + */
9.140 + private static class SentinelHolder {
9.141 + /**
9.142 + * {@linkplain #setStackTrace(StackTraceElement[]) Setting the
9.143 + * stack trace} to a one-element array containing this sentinel
9.144 + * value indicates future attempts to set the stack trace will be
9.145 + * ignored. The sentinal is equal to the result of calling:<br>
9.146 + * {@code new StackTraceElement("", "", null, Integer.MIN_VALUE)}
9.147 + */
9.148 + public static final StackTraceElement STACK_TRACE_ELEMENT_SENTINEL =
9.149 + new StackTraceElement("", "", null, Integer.MIN_VALUE);
9.150 +
9.151 + /**
9.152 + * Sentinel value used in the serial form to indicate an immutable
9.153 + * stack trace.
9.154 + */
9.155 + public static final StackTraceElement[] STACK_TRACE_SENTINEL =
9.156 + new StackTraceElement[] {STACK_TRACE_ELEMENT_SENTINEL};
9.157 + }
9.158 +
9.159 + /**
9.160 + * A shared value for an empty stack.
9.161 + */
9.162 + private static final StackTraceElement[] UNASSIGNED_STACK = new StackTraceElement[0];
9.163 +
9.164 + /*
9.165 + * To allow Throwable objects to be made immutable and safely
9.166 + * reused by the JVM, such as OutOfMemoryErrors, fields of
9.167 + * Throwable that are writable in response to user actions, cause,
9.168 + * stackTrace, and suppressedExceptions obey the following
9.169 + * protocol:
9.170 + *
9.171 + * 1) The fields are initialized to a non-null sentinel value
9.172 + * which indicates the value has logically not been set.
9.173 + *
9.174 + * 2) Writing a null to the field indicates further writes
9.175 + * are forbidden
9.176 + *
9.177 + * 3) The sentinel value may be replaced with another non-null
9.178 + * value.
9.179 + *
9.180 + * For example, implementations of the HotSpot JVM have
9.181 + * preallocated OutOfMemoryError objects to provide for better
9.182 + * diagnosability of that situation. These objects are created
9.183 + * without calling the constructor for that class and the fields
9.184 + * in question are initialized to null. To support this
9.185 + * capability, any new fields added to Throwable that require
9.186 + * being initialized to a non-null value require a coordinated JVM
9.187 + * change.
9.188 + */
9.189 +
9.190 + /**
9.191 + * The throwable that caused this throwable to get thrown, or null if this
9.192 + * throwable was not caused by another throwable, or if the causative
9.193 + * throwable is unknown. If this field is equal to this throwable itself,
9.194 + * it indicates that the cause of this throwable has not yet been
9.195 + * initialized.
9.196 + *
9.197 + * @serial
9.198 + * @since 1.4
9.199 + */
9.200 + private Throwable cause = this;
9.201 +
9.202 + /**
9.203 + * The stack trace, as returned by {@link #getStackTrace()}.
9.204 + *
9.205 + * The field is initialized to a zero-length array. A {@code
9.206 + * null} value of this field indicates subsequent calls to {@link
9.207 + * #setStackTrace(StackTraceElement[])} and {@link
9.208 + * #fillInStackTrace()} will be be no-ops.
9.209 + *
9.210 + * @serial
9.211 + * @since 1.4
9.212 + */
9.213 + private StackTraceElement[] stackTrace = UNASSIGNED_STACK;
9.214 +
9.215 + // Setting this static field introduces an acceptable
9.216 + // initialization dependency on a few java.util classes.
9.217 + private static final List<Throwable> SUPPRESSED_SENTINEL =
9.218 + Collections.unmodifiableList(new ArrayList<Throwable>(0));
9.219 +
9.220 + /**
9.221 + * The list of suppressed exceptions, as returned by {@link
9.222 + * #getSuppressed()}. The list is initialized to a zero-element
9.223 + * unmodifiable sentinel list. When a serialized Throwable is
9.224 + * read in, if the {@code suppressedExceptions} field points to a
9.225 + * zero-element list, the field is reset to the sentinel value.
9.226 + *
9.227 + * @serial
9.228 + * @since 1.7
9.229 + */
9.230 + private List<Throwable> suppressedExceptions = SUPPRESSED_SENTINEL;
9.231 +
9.232 + /** Message for trying to suppress a null exception. */
9.233 + private static final String NULL_CAUSE_MESSAGE = "Cannot suppress a null exception.";
9.234 +
9.235 + /** Message for trying to suppress oneself. */
9.236 + private static final String SELF_SUPPRESSION_MESSAGE = "Self-suppression not permitted";
9.237 +
9.238 + /** Caption for labeling causative exception stack traces */
9.239 + private static final String CAUSE_CAPTION = "Caused by: ";
9.240 +
9.241 + /** Caption for labeling suppressed exception stack traces */
9.242 + private static final String SUPPRESSED_CAPTION = "Suppressed: ";
9.243 +
9.244 + /**
9.245 + * Constructs a new throwable with {@code null} as its detail message.
9.246 + * The cause is not initialized, and may subsequently be initialized by a
9.247 + * call to {@link #initCause}.
9.248 + *
9.249 + * <p>The {@link #fillInStackTrace()} method is called to initialize
9.250 + * the stack trace data in the newly created throwable.
9.251 + */
9.252 + public Throwable() {
9.253 + fillInStackTrace();
9.254 + }
9.255 +
9.256 + /**
9.257 + * Constructs a new throwable with the specified detail message. The
9.258 + * cause is not initialized, and may subsequently be initialized by
9.259 + * a call to {@link #initCause}.
9.260 + *
9.261 + * <p>The {@link #fillInStackTrace()} method is called to initialize
9.262 + * the stack trace data in the newly created throwable.
9.263 + *
9.264 + * @param message the detail message. The detail message is saved for
9.265 + * later retrieval by the {@link #getMessage()} method.
9.266 + */
9.267 + public Throwable(String message) {
9.268 + fillInStackTrace();
9.269 + detailMessage = message;
9.270 + }
9.271 +
9.272 + /**
9.273 + * Constructs a new throwable with the specified detail message and
9.274 + * cause. <p>Note that the detail message associated with
9.275 + * {@code cause} is <i>not</i> automatically incorporated in
9.276 + * this throwable's detail message.
9.277 + *
9.278 + * <p>The {@link #fillInStackTrace()} method is called to initialize
9.279 + * the stack trace data in the newly created throwable.
9.280 + *
9.281 + * @param message the detail message (which is saved for later retrieval
9.282 + * by the {@link #getMessage()} method).
9.283 + * @param cause the cause (which is saved for later retrieval by the
9.284 + * {@link #getCause()} method). (A {@code null} value is
9.285 + * permitted, and indicates that the cause is nonexistent or
9.286 + * unknown.)
9.287 + * @since 1.4
9.288 + */
9.289 + public Throwable(String message, Throwable cause) {
9.290 + fillInStackTrace();
9.291 + detailMessage = message;
9.292 + this.cause = cause;
9.293 + }
9.294 +
9.295 + /**
9.296 + * Constructs a new throwable with the specified cause and a detail
9.297 + * message of {@code (cause==null ? null : cause.toString())} (which
9.298 + * typically contains the class and detail message of {@code cause}).
9.299 + * This constructor is useful for throwables that are little more than
9.300 + * wrappers for other throwables (for example, {@link
9.301 + * java.security.PrivilegedActionException}).
9.302 + *
9.303 + * <p>The {@link #fillInStackTrace()} method is called to initialize
9.304 + * the stack trace data in the newly created throwable.
9.305 + *
9.306 + * @param cause the cause (which is saved for later retrieval by the
9.307 + * {@link #getCause()} method). (A {@code null} value is
9.308 + * permitted, and indicates that the cause is nonexistent or
9.309 + * unknown.)
9.310 + * @since 1.4
9.311 + */
9.312 + public Throwable(Throwable cause) {
9.313 + fillInStackTrace();
9.314 + detailMessage = (cause==null ? null : cause.toString());
9.315 + this.cause = cause;
9.316 + }
9.317 +
9.318 + /**
9.319 + * Constructs a new throwable with the specified detail message,
9.320 + * cause, {@linkplain #addSuppressed suppression} enabled or
9.321 + * disabled, and writable stack trace enabled or disabled. If
9.322 + * suppression is disabled, {@link #getSuppressed} for this object
9.323 + * will return a zero-length array and calls to {@link
9.324 + * #addSuppressed} that would otherwise append an exception to the
9.325 + * suppressed list will have no effect. If the writable stack
9.326 + * trace is false, this constructor will not call {@link
9.327 + * #fillInStackTrace()}, a {@code null} will be written to the
9.328 + * {@code stackTrace} field, and subsequent calls to {@code
9.329 + * fillInStackTrace} and {@link
9.330 + * #setStackTrace(StackTraceElement[])} will not set the stack
9.331 + * trace. If the writable stack trace is false, {@link
9.332 + * #getStackTrace} will return a zero length array.
9.333 + *
9.334 + * <p>Note that the other constructors of {@code Throwable} treat
9.335 + * suppression as being enabled and the stack trace as being
9.336 + * writable. Subclasses of {@code Throwable} should document any
9.337 + * conditions under which suppression is disabled and document
9.338 + * conditions under which the stack trace is not writable.
9.339 + * Disabling of suppression should only occur in exceptional
9.340 + * circumstances where special requirements exist, such as a
9.341 + * virtual machine reusing exception objects under low-memory
9.342 + * situations. Circumstances where a given exception object is
9.343 + * repeatedly caught and rethrown, such as to implement control
9.344 + * flow between two sub-systems, is another situation where
9.345 + * immutable throwable objects would be appropriate.
9.346 + *
9.347 + * @param message the detail message.
9.348 + * @param cause the cause. (A {@code null} value is permitted,
9.349 + * and indicates that the cause is nonexistent or unknown.)
9.350 + * @param enableSuppression whether or not suppression is enabled or disabled
9.351 + * @param writableStackTrace whether or not the stack trace should be
9.352 + * writable
9.353 + *
9.354 + * @see OutOfMemoryError
9.355 + * @see NullPointerException
9.356 + * @see ArithmeticException
9.357 + * @since 1.7
9.358 + */
9.359 + protected Throwable(String message, Throwable cause,
9.360 + boolean enableSuppression,
9.361 + boolean writableStackTrace) {
9.362 + if (writableStackTrace) {
9.363 + fillInStackTrace();
9.364 + } else {
9.365 + stackTrace = null;
9.366 + }
9.367 + detailMessage = message;
9.368 + this.cause = cause;
9.369 + if (!enableSuppression)
9.370 + suppressedExceptions = null;
9.371 + }
9.372 +
9.373 + /**
9.374 + * Returns the detail message string of this throwable.
9.375 + *
9.376 + * @return the detail message string of this {@code Throwable} instance
9.377 + * (which may be {@code null}).
9.378 + */
9.379 + public String getMessage() {
9.380 + return detailMessage;
9.381 + }
9.382 +
9.383 + /**
9.384 + * Creates a localized description of this throwable.
9.385 + * Subclasses may override this method in order to produce a
9.386 + * locale-specific message. For subclasses that do not override this
9.387 + * method, the default implementation returns the same result as
9.388 + * {@code getMessage()}.
9.389 + *
9.390 + * @return The localized description of this throwable.
9.391 + * @since JDK1.1
9.392 + */
9.393 + public String getLocalizedMessage() {
9.394 + return getMessage();
9.395 + }
9.396 +
9.397 + /**
9.398 + * Returns the cause of this throwable or {@code null} if the
9.399 + * cause is nonexistent or unknown. (The cause is the throwable that
9.400 + * caused this throwable to get thrown.)
9.401 + *
9.402 + * <p>This implementation returns the cause that was supplied via one of
9.403 + * the constructors requiring a {@code Throwable}, or that was set after
9.404 + * creation with the {@link #initCause(Throwable)} method. While it is
9.405 + * typically unnecessary to override this method, a subclass can override
9.406 + * it to return a cause set by some other means. This is appropriate for
9.407 + * a "legacy chained throwable" that predates the addition of chained
9.408 + * exceptions to {@code Throwable}. Note that it is <i>not</i>
9.409 + * necessary to override any of the {@code PrintStackTrace} methods,
9.410 + * all of which invoke the {@code getCause} method to determine the
9.411 + * cause of a throwable.
9.412 + *
9.413 + * @return the cause of this throwable or {@code null} if the
9.414 + * cause is nonexistent or unknown.
9.415 + * @since 1.4
9.416 + */
9.417 + public synchronized Throwable getCause() {
9.418 + return (cause==this ? null : cause);
9.419 + }
9.420 +
9.421 + /**
9.422 + * Initializes the <i>cause</i> of this throwable to the specified value.
9.423 + * (The cause is the throwable that caused this throwable to get thrown.)
9.424 + *
9.425 + * <p>This method can be called at most once. It is generally called from
9.426 + * within the constructor, or immediately after creating the
9.427 + * throwable. If this throwable was created
9.428 + * with {@link #Throwable(Throwable)} or
9.429 + * {@link #Throwable(String,Throwable)}, this method cannot be called
9.430 + * even once.
9.431 + *
9.432 + * <p>An example of using this method on a legacy throwable type
9.433 + * without other support for setting the cause is:
9.434 + *
9.435 + * <pre>
9.436 + * try {
9.437 + * lowLevelOp();
9.438 + * } catch (LowLevelException le) {
9.439 + * throw (HighLevelException)
9.440 + * new HighLevelException().initCause(le); // Legacy constructor
9.441 + * }
9.442 + * </pre>
9.443 + *
9.444 + * @param cause the cause (which is saved for later retrieval by the
9.445 + * {@link #getCause()} method). (A {@code null} value is
9.446 + * permitted, and indicates that the cause is nonexistent or
9.447 + * unknown.)
9.448 + * @return a reference to this {@code Throwable} instance.
9.449 + * @throws IllegalArgumentException if {@code cause} is this
9.450 + * throwable. (A throwable cannot be its own cause.)
9.451 + * @throws IllegalStateException if this throwable was
9.452 + * created with {@link #Throwable(Throwable)} or
9.453 + * {@link #Throwable(String,Throwable)}, or this method has already
9.454 + * been called on this throwable.
9.455 + * @since 1.4
9.456 + */
9.457 + public synchronized Throwable initCause(Throwable cause) {
9.458 + if (this.cause != this)
9.459 + throw new IllegalStateException("Can't overwrite cause");
9.460 + if (cause == this)
9.461 + throw new IllegalArgumentException("Self-causation not permitted");
9.462 + this.cause = cause;
9.463 + return this;
9.464 + }
9.465 +
9.466 + /**
9.467 + * Returns a short description of this throwable.
9.468 + * The result is the concatenation of:
9.469 + * <ul>
9.470 + * <li> the {@linkplain Class#getName() name} of the class of this object
9.471 + * <li> ": " (a colon and a space)
9.472 + * <li> the result of invoking this object's {@link #getLocalizedMessage}
9.473 + * method
9.474 + * </ul>
9.475 + * If {@code getLocalizedMessage} returns {@code null}, then just
9.476 + * the class name is returned.
9.477 + *
9.478 + * @return a string representation of this throwable.
9.479 + */
9.480 + public String toString() {
9.481 + String s = getClass().getName();
9.482 + String message = getLocalizedMessage();
9.483 + return (message != null) ? (s + ": " + message) : s;
9.484 + }
9.485 +
9.486 + /**
9.487 + * Prints this throwable and its backtrace to the
9.488 + * standard error stream. This method prints a stack trace for this
9.489 + * {@code Throwable} object on the error output stream that is
9.490 + * the value of the field {@code System.err}. The first line of
9.491 + * output contains the result of the {@link #toString()} method for
9.492 + * this object. Remaining lines represent data previously recorded by
9.493 + * the method {@link #fillInStackTrace()}. The format of this
9.494 + * information depends on the implementation, but the following
9.495 + * example may be regarded as typical:
9.496 + * <blockquote><pre>
9.497 + * java.lang.NullPointerException
9.498 + * at MyClass.mash(MyClass.java:9)
9.499 + * at MyClass.crunch(MyClass.java:6)
9.500 + * at MyClass.main(MyClass.java:3)
9.501 + * </pre></blockquote>
9.502 + * This example was produced by running the program:
9.503 + * <pre>
9.504 + * class MyClass {
9.505 + * public static void main(String[] args) {
9.506 + * crunch(null);
9.507 + * }
9.508 + * static void crunch(int[] a) {
9.509 + * mash(a);
9.510 + * }
9.511 + * static void mash(int[] b) {
9.512 + * System.out.println(b[0]);
9.513 + * }
9.514 + * }
9.515 + * </pre>
9.516 + * The backtrace for a throwable with an initialized, non-null cause
9.517 + * should generally include the backtrace for the cause. The format
9.518 + * of this information depends on the implementation, but the following
9.519 + * example may be regarded as typical:
9.520 + * <pre>
9.521 + * HighLevelException: MidLevelException: LowLevelException
9.522 + * at Junk.a(Junk.java:13)
9.523 + * at Junk.main(Junk.java:4)
9.524 + * Caused by: MidLevelException: LowLevelException
9.525 + * at Junk.c(Junk.java:23)
9.526 + * at Junk.b(Junk.java:17)
9.527 + * at Junk.a(Junk.java:11)
9.528 + * ... 1 more
9.529 + * Caused by: LowLevelException
9.530 + * at Junk.e(Junk.java:30)
9.531 + * at Junk.d(Junk.java:27)
9.532 + * at Junk.c(Junk.java:21)
9.533 + * ... 3 more
9.534 + * </pre>
9.535 + * Note the presence of lines containing the characters {@code "..."}.
9.536 + * These lines indicate that the remainder of the stack trace for this
9.537 + * exception matches the indicated number of frames from the bottom of the
9.538 + * stack trace of the exception that was caused by this exception (the
9.539 + * "enclosing" exception). This shorthand can greatly reduce the length
9.540 + * of the output in the common case where a wrapped exception is thrown
9.541 + * from same method as the "causative exception" is caught. The above
9.542 + * example was produced by running the program:
9.543 + * <pre>
9.544 + * public class Junk {
9.545 + * public static void main(String args[]) {
9.546 + * try {
9.547 + * a();
9.548 + * } catch(HighLevelException e) {
9.549 + * e.printStackTrace();
9.550 + * }
9.551 + * }
9.552 + * static void a() throws HighLevelException {
9.553 + * try {
9.554 + * b();
9.555 + * } catch(MidLevelException e) {
9.556 + * throw new HighLevelException(e);
9.557 + * }
9.558 + * }
9.559 + * static void b() throws MidLevelException {
9.560 + * c();
9.561 + * }
9.562 + * static void c() throws MidLevelException {
9.563 + * try {
9.564 + * d();
9.565 + * } catch(LowLevelException e) {
9.566 + * throw new MidLevelException(e);
9.567 + * }
9.568 + * }
9.569 + * static void d() throws LowLevelException {
9.570 + * e();
9.571 + * }
9.572 + * static void e() throws LowLevelException {
9.573 + * throw new LowLevelException();
9.574 + * }
9.575 + * }
9.576 + *
9.577 + * class HighLevelException extends Exception {
9.578 + * HighLevelException(Throwable cause) { super(cause); }
9.579 + * }
9.580 + *
9.581 + * class MidLevelException extends Exception {
9.582 + * MidLevelException(Throwable cause) { super(cause); }
9.583 + * }
9.584 + *
9.585 + * class LowLevelException extends Exception {
9.586 + * }
9.587 + * </pre>
9.588 + * As of release 7, the platform supports the notion of
9.589 + * <i>suppressed exceptions</i> (in conjunction with the {@code
9.590 + * try}-with-resources statement). Any exceptions that were
9.591 + * suppressed in order to deliver an exception are printed out
9.592 + * beneath the stack trace. The format of this information
9.593 + * depends on the implementation, but the following example may be
9.594 + * regarded as typical:
9.595 + *
9.596 + * <pre>
9.597 + * Exception in thread "main" java.lang.Exception: Something happened
9.598 + * at Foo.bar(Foo.java:10)
9.599 + * at Foo.main(Foo.java:5)
9.600 + * Suppressed: Resource$CloseFailException: Resource ID = 0
9.601 + * at Resource.close(Resource.java:26)
9.602 + * at Foo.bar(Foo.java:9)
9.603 + * ... 1 more
9.604 + * </pre>
9.605 + * Note that the "... n more" notation is used on suppressed exceptions
9.606 + * just at it is used on causes. Unlike causes, suppressed exceptions are
9.607 + * indented beyond their "containing exceptions."
9.608 + *
9.609 + * <p>An exception can have both a cause and one or more suppressed
9.610 + * exceptions:
9.611 + * <pre>
9.612 + * Exception in thread "main" java.lang.Exception: Main block
9.613 + * at Foo3.main(Foo3.java:7)
9.614 + * Suppressed: Resource$CloseFailException: Resource ID = 2
9.615 + * at Resource.close(Resource.java:26)
9.616 + * at Foo3.main(Foo3.java:5)
9.617 + * Suppressed: Resource$CloseFailException: Resource ID = 1
9.618 + * at Resource.close(Resource.java:26)
9.619 + * at Foo3.main(Foo3.java:5)
9.620 + * Caused by: java.lang.Exception: I did it
9.621 + * at Foo3.main(Foo3.java:8)
9.622 + * </pre>
9.623 + * Likewise, a suppressed exception can have a cause:
9.624 + * <pre>
9.625 + * Exception in thread "main" java.lang.Exception: Main block
9.626 + * at Foo4.main(Foo4.java:6)
9.627 + * Suppressed: Resource2$CloseFailException: Resource ID = 1
9.628 + * at Resource2.close(Resource2.java:20)
9.629 + * at Foo4.main(Foo4.java:5)
9.630 + * Caused by: java.lang.Exception: Rats, you caught me
9.631 + * at Resource2$CloseFailException.<init>(Resource2.java:45)
9.632 + * ... 2 more
9.633 + * </pre>
9.634 + */
9.635 + public void printStackTrace() {
9.636 + printStackTrace(System.err);
9.637 + }
9.638 +
9.639 + /**
9.640 + * Prints this throwable and its backtrace to the specified print stream.
9.641 + *
9.642 + * @param s {@code PrintStream} to use for output
9.643 + */
9.644 + public void printStackTrace(PrintStream s) {
9.645 + printStackTrace(new WrappedPrintStream(s));
9.646 + }
9.647 +
9.648 + private void printStackTrace(PrintStreamOrWriter s) {
9.649 + // Guard against malicious overrides of Throwable.equals by
9.650 + // using a Set with identity equality semantics.
9.651 + Set<Throwable> dejaVu =
9.652 + Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
9.653 + dejaVu.add(this);
9.654 +
9.655 + synchronized (s.lock()) {
9.656 + // Print our stack trace
9.657 + s.println(this);
9.658 + StackTraceElement[] trace = getOurStackTrace();
9.659 + for (StackTraceElement traceElement : trace)
9.660 + s.println("\tat " + traceElement);
9.661 +
9.662 + // Print suppressed exceptions, if any
9.663 + for (Throwable se : getSuppressed())
9.664 + se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION, "\t", dejaVu);
9.665 +
9.666 + // Print cause, if any
9.667 + Throwable ourCause = getCause();
9.668 + if (ourCause != null)
9.669 + ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, "", dejaVu);
9.670 + }
9.671 + }
9.672 +
9.673 + /**
9.674 + * Print our stack trace as an enclosed exception for the specified
9.675 + * stack trace.
9.676 + */
9.677 + private void printEnclosedStackTrace(PrintStreamOrWriter s,
9.678 + StackTraceElement[] enclosingTrace,
9.679 + String caption,
9.680 + String prefix,
9.681 + Set<Throwable> dejaVu) {
9.682 + assert Thread.holdsLock(s.lock());
9.683 + if (dejaVu.contains(this)) {
9.684 + s.println("\t[CIRCULAR REFERENCE:" + this + "]");
9.685 + } else {
9.686 + dejaVu.add(this);
9.687 + // Compute number of frames in common between this and enclosing trace
9.688 + StackTraceElement[] trace = getOurStackTrace();
9.689 + int m = trace.length - 1;
9.690 + int n = enclosingTrace.length - 1;
9.691 + while (m >= 0 && n >=0 && trace[m].equals(enclosingTrace[n])) {
9.692 + m--; n--;
9.693 + }
9.694 + int framesInCommon = trace.length - 1 - m;
9.695 +
9.696 + // Print our stack trace
9.697 + s.println(prefix + caption + this);
9.698 + for (int i = 0; i <= m; i++)
9.699 + s.println(prefix + "\tat " + trace[i]);
9.700 + if (framesInCommon != 0)
9.701 + s.println(prefix + "\t... " + framesInCommon + " more");
9.702 +
9.703 + // Print suppressed exceptions, if any
9.704 + for (Throwable se : getSuppressed())
9.705 + se.printEnclosedStackTrace(s, trace, SUPPRESSED_CAPTION,
9.706 + prefix +"\t", dejaVu);
9.707 +
9.708 + // Print cause, if any
9.709 + Throwable ourCause = getCause();
9.710 + if (ourCause != null)
9.711 + ourCause.printEnclosedStackTrace(s, trace, CAUSE_CAPTION, prefix, dejaVu);
9.712 + }
9.713 + }
9.714 +
9.715 + /**
9.716 + * Prints this throwable and its backtrace to the specified
9.717 + * print writer.
9.718 + *
9.719 + * @param s {@code PrintWriter} to use for output
9.720 + * @since JDK1.1
9.721 + */
9.722 + public void printStackTrace(PrintWriter s) {
9.723 + printStackTrace(new WrappedPrintWriter(s));
9.724 + }
9.725 +
9.726 + /**
9.727 + * Wrapper class for PrintStream and PrintWriter to enable a single
9.728 + * implementation of printStackTrace.
9.729 + */
9.730 + private abstract static class PrintStreamOrWriter {
9.731 + /** Returns the object to be locked when using this StreamOrWriter */
9.732 + abstract Object lock();
9.733 +
9.734 + /** Prints the specified string as a line on this StreamOrWriter */
9.735 + abstract void println(Object o);
9.736 + }
9.737 +
9.738 + private static class WrappedPrintStream extends PrintStreamOrWriter {
9.739 + private final PrintStream printStream;
9.740 +
9.741 + WrappedPrintStream(PrintStream printStream) {
9.742 + this.printStream = printStream;
9.743 + }
9.744 +
9.745 + Object lock() {
9.746 + return printStream;
9.747 + }
9.748 +
9.749 + void println(Object o) {
9.750 + printStream.println(o);
9.751 + }
9.752 + }
9.753 +
9.754 + private static class WrappedPrintWriter extends PrintStreamOrWriter {
9.755 + private final PrintWriter printWriter;
9.756 +
9.757 + WrappedPrintWriter(PrintWriter printWriter) {
9.758 + this.printWriter = printWriter;
9.759 + }
9.760 +
9.761 + Object lock() {
9.762 + return printWriter;
9.763 + }
9.764 +
9.765 + void println(Object o) {
9.766 + printWriter.println(o);
9.767 + }
9.768 + }
9.769 +
9.770 + /**
9.771 + * Fills in the execution stack trace. This method records within this
9.772 + * {@code Throwable} object information about the current state of
9.773 + * the stack frames for the current thread.
9.774 + *
9.775 + * <p>If the stack trace of this {@code Throwable} {@linkplain
9.776 + * Throwable#Throwable(String, Throwable, boolean, boolean) is not
9.777 + * writable}, calling this method has no effect.
9.778 + *
9.779 + * @return a reference to this {@code Throwable} instance.
9.780 + * @see java.lang.Throwable#printStackTrace()
9.781 + */
9.782 + public synchronized Throwable fillInStackTrace() {
9.783 + if (stackTrace != null ||
9.784 + backtrace != null /* Out of protocol state */ ) {
9.785 + fillInStackTrace(0);
9.786 + stackTrace = UNASSIGNED_STACK;
9.787 + }
9.788 + return this;
9.789 + }
9.790 +
9.791 + private native Throwable fillInStackTrace(int dummy);
9.792 +
9.793 + /**
9.794 + * Provides programmatic access to the stack trace information printed by
9.795 + * {@link #printStackTrace()}. Returns an array of stack trace elements,
9.796 + * each representing one stack frame. The zeroth element of the array
9.797 + * (assuming the array's length is non-zero) represents the top of the
9.798 + * stack, which is the last method invocation in the sequence. Typically,
9.799 + * this is the point at which this throwable was created and thrown.
9.800 + * The last element of the array (assuming the array's length is non-zero)
9.801 + * represents the bottom of the stack, which is the first method invocation
9.802 + * in the sequence.
9.803 + *
9.804 + * <p>Some virtual machines may, under some circumstances, omit one
9.805 + * or more stack frames from the stack trace. In the extreme case,
9.806 + * a virtual machine that has no stack trace information concerning
9.807 + * this throwable is permitted to return a zero-length array from this
9.808 + * method. Generally speaking, the array returned by this method will
9.809 + * contain one element for every frame that would be printed by
9.810 + * {@code printStackTrace}. Writes to the returned array do not
9.811 + * affect future calls to this method.
9.812 + *
9.813 + * @return an array of stack trace elements representing the stack trace
9.814 + * pertaining to this throwable.
9.815 + * @since 1.4
9.816 + */
9.817 + public StackTraceElement[] getStackTrace() {
9.818 + return getOurStackTrace().clone();
9.819 + }
9.820 +
9.821 + private synchronized StackTraceElement[] getOurStackTrace() {
9.822 + // Initialize stack trace field with information from
9.823 + // backtrace if this is the first call to this method
9.824 + if (stackTrace == UNASSIGNED_STACK ||
9.825 + (stackTrace == null && backtrace != null) /* Out of protocol state */) {
9.826 + int depth = getStackTraceDepth();
9.827 + stackTrace = new StackTraceElement[depth];
9.828 + for (int i=0; i < depth; i++)
9.829 + stackTrace[i] = getStackTraceElement(i);
9.830 + } else if (stackTrace == null) {
9.831 + return UNASSIGNED_STACK;
9.832 + }
9.833 + return stackTrace;
9.834 + }
9.835 +
9.836 + /**
9.837 + * Sets the stack trace elements that will be returned by
9.838 + * {@link #getStackTrace()} and printed by {@link #printStackTrace()}
9.839 + * and related methods.
9.840 + *
9.841 + * This method, which is designed for use by RPC frameworks and other
9.842 + * advanced systems, allows the client to override the default
9.843 + * stack trace that is either generated by {@link #fillInStackTrace()}
9.844 + * when a throwable is constructed or deserialized when a throwable is
9.845 + * read from a serialization stream.
9.846 + *
9.847 + * <p>If the stack trace of this {@code Throwable} {@linkplain
9.848 + * Throwable#Throwable(String, Throwable, boolean, boolean) is not
9.849 + * writable}, calling this method has no effect other than
9.850 + * validating its argument.
9.851 + *
9.852 + * @param stackTrace the stack trace elements to be associated with
9.853 + * this {@code Throwable}. The specified array is copied by this
9.854 + * call; changes in the specified array after the method invocation
9.855 + * returns will have no affect on this {@code Throwable}'s stack
9.856 + * trace.
9.857 + *
9.858 + * @throws NullPointerException if {@code stackTrace} is
9.859 + * {@code null} or if any of the elements of
9.860 + * {@code stackTrace} are {@code null}
9.861 + *
9.862 + * @since 1.4
9.863 + */
9.864 + public void setStackTrace(StackTraceElement[] stackTrace) {
9.865 + // Validate argument
9.866 + StackTraceElement[] defensiveCopy = stackTrace.clone();
9.867 + for (int i = 0; i < defensiveCopy.length; i++) {
9.868 + if (defensiveCopy[i] == null)
9.869 + throw new NullPointerException("stackTrace[" + i + "]");
9.870 + }
9.871 +
9.872 + synchronized (this) {
9.873 + if (this.stackTrace == null && // Immutable stack
9.874 + backtrace == null) // Test for out of protocol state
9.875 + return;
9.876 + this.stackTrace = defensiveCopy;
9.877 + }
9.878 + }
9.879 +
9.880 + /**
9.881 + * Returns the number of elements in the stack trace (or 0 if the stack
9.882 + * trace is unavailable).
9.883 + *
9.884 + * package-protection for use by SharedSecrets.
9.885 + */
9.886 + native int getStackTraceDepth();
9.887 +
9.888 + /**
9.889 + * Returns the specified element of the stack trace.
9.890 + *
9.891 + * package-protection for use by SharedSecrets.
9.892 + *
9.893 + * @param index index of the element to return.
9.894 + * @throws IndexOutOfBoundsException if {@code index < 0 ||
9.895 + * index >= getStackTraceDepth() }
9.896 + */
9.897 + native StackTraceElement getStackTraceElement(int index);
9.898 +
9.899 + /**
9.900 + * Reads a {@code Throwable} from a stream, enforcing
9.901 + * well-formedness constraints on fields. Null entries and
9.902 + * self-pointers are not allowed in the list of {@code
9.903 + * suppressedExceptions}. Null entries are not allowed for stack
9.904 + * trace elements. A null stack trace in the serial form results
9.905 + * in a zero-length stack element array. A single-element stack
9.906 + * trace whose entry is equal to {@code new StackTraceElement("",
9.907 + * "", null, Integer.MIN_VALUE)} results in a {@code null} {@code
9.908 + * stackTrace} field.
9.909 + *
9.910 + * Note that there are no constraints on the value the {@code
9.911 + * cause} field can hold; both {@code null} and {@code this} are
9.912 + * valid values for the field.
9.913 + */
9.914 + private void readObject(ObjectInputStream s)
9.915 + throws IOException, ClassNotFoundException {
9.916 + s.defaultReadObject(); // read in all fields
9.917 + if (suppressedExceptions != null) {
9.918 + List<Throwable> suppressed = null;
9.919 + if (suppressedExceptions.isEmpty()) {
9.920 + // Use the sentinel for a zero-length list
9.921 + suppressed = SUPPRESSED_SENTINEL;
9.922 + } else { // Copy Throwables to new list
9.923 + suppressed = new ArrayList<>(1);
9.924 + for (Throwable t : suppressedExceptions) {
9.925 + // Enforce constraints on suppressed exceptions in
9.926 + // case of corrupt or malicious stream.
9.927 + if (t == null)
9.928 + throw new NullPointerException(NULL_CAUSE_MESSAGE);
9.929 + if (t == this)
9.930 + throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
9.931 + suppressed.add(t);
9.932 + }
9.933 + }
9.934 + suppressedExceptions = suppressed;
9.935 + } // else a null suppressedExceptions field remains null
9.936 +
9.937 + /*
9.938 + * For zero-length stack traces, use a clone of
9.939 + * UNASSIGNED_STACK rather than UNASSIGNED_STACK itself to
9.940 + * allow identity comparison against UNASSIGNED_STACK in
9.941 + * getOurStackTrace. The identity of UNASSIGNED_STACK in
9.942 + * stackTrace indicates to the getOurStackTrace method that
9.943 + * the stackTrace needs to be constructed from the information
9.944 + * in backtrace.
9.945 + */
9.946 + if (stackTrace != null) {
9.947 + if (stackTrace.length == 0) {
9.948 + stackTrace = UNASSIGNED_STACK.clone();
9.949 + } else if (stackTrace.length == 1 &&
9.950 + // Check for the marker of an immutable stack trace
9.951 + SentinelHolder.STACK_TRACE_ELEMENT_SENTINEL.equals(stackTrace[0])) {
9.952 + stackTrace = null;
9.953 + } else { // Verify stack trace elements are non-null.
9.954 + for(StackTraceElement ste : stackTrace) {
9.955 + if (ste == null)
9.956 + throw new NullPointerException("null StackTraceElement in serial stream. ");
9.957 + }
9.958 + }
9.959 + } else {
9.960 + // A null stackTrace field in the serial form can result
9.961 + // from an exception serialized without that field in
9.962 + // older JDK releases; treat such exceptions as having
9.963 + // empty stack traces.
9.964 + stackTrace = UNASSIGNED_STACK.clone();
9.965 + }
9.966 + }
9.967 +
9.968 + /**
9.969 + * Write a {@code Throwable} object to a stream.
9.970 + *
9.971 + * A {@code null} stack trace field is represented in the serial
9.972 + * form as a one-element array whose element is equal to {@code
9.973 + * new StackTraceElement("", "", null, Integer.MIN_VALUE)}.
9.974 + */
9.975 + private synchronized void writeObject(ObjectOutputStream s)
9.976 + throws IOException {
9.977 + // Ensure that the stackTrace field is initialized to a
9.978 + // non-null value, if appropriate. As of JDK 7, a null stack
9.979 + // trace field is a valid value indicating the stack trace
9.980 + // should not be set.
9.981 + getOurStackTrace();
9.982 +
9.983 + StackTraceElement[] oldStackTrace = stackTrace;
9.984 + try {
9.985 + if (stackTrace == null)
9.986 + stackTrace = SentinelHolder.STACK_TRACE_SENTINEL;
9.987 + s.defaultWriteObject();
9.988 + } finally {
9.989 + stackTrace = oldStackTrace;
9.990 + }
9.991 + }
9.992 +
9.993 + /**
9.994 + * Appends the specified exception to the exceptions that were
9.995 + * suppressed in order to deliver this exception. This method is
9.996 + * thread-safe and typically called (automatically and implicitly)
9.997 + * by the {@code try}-with-resources statement.
9.998 + *
9.999 + * <p>The suppression behavior is enabled <em>unless</em> disabled
9.1000 + * {@linkplain #Throwable(String, Throwable, boolean, boolean) via
9.1001 + * a constructor}. When suppression is disabled, this method does
9.1002 + * nothing other than to validate its argument.
9.1003 + *
9.1004 + * <p>Note that when one exception {@linkplain
9.1005 + * #initCause(Throwable) causes} another exception, the first
9.1006 + * exception is usually caught and then the second exception is
9.1007 + * thrown in response. In other words, there is a causal
9.1008 + * connection between the two exceptions.
9.1009 + *
9.1010 + * In contrast, there are situations where two independent
9.1011 + * exceptions can be thrown in sibling code blocks, in particular
9.1012 + * in the {@code try} block of a {@code try}-with-resources
9.1013 + * statement and the compiler-generated {@code finally} block
9.1014 + * which closes the resource.
9.1015 + *
9.1016 + * In these situations, only one of the thrown exceptions can be
9.1017 + * propagated. In the {@code try}-with-resources statement, when
9.1018 + * there are two such exceptions, the exception originating from
9.1019 + * the {@code try} block is propagated and the exception from the
9.1020 + * {@code finally} block is added to the list of exceptions
9.1021 + * suppressed by the exception from the {@code try} block. As an
9.1022 + * exception unwinds the stack, it can accumulate multiple
9.1023 + * suppressed exceptions.
9.1024 + *
9.1025 + * <p>An exception may have suppressed exceptions while also being
9.1026 + * caused by another exception. Whether or not an exception has a
9.1027 + * cause is semantically known at the time of its creation, unlike
9.1028 + * whether or not an exception will suppress other exceptions
9.1029 + * which is typically only determined after an exception is
9.1030 + * thrown.
9.1031 + *
9.1032 + * <p>Note that programmer written code is also able to take
9.1033 + * advantage of calling this method in situations where there are
9.1034 + * multiple sibling exceptions and only one can be propagated.
9.1035 + *
9.1036 + * @param exception the exception to be added to the list of
9.1037 + * suppressed exceptions
9.1038 + * @throws IllegalArgumentException if {@code exception} is this
9.1039 + * throwable; a throwable cannot suppress itself.
9.1040 + * @throws NullPointerException if {@code exception} is {@code null}
9.1041 + * @since 1.7
9.1042 + */
9.1043 + public final synchronized void addSuppressed(Throwable exception) {
9.1044 + if (exception == this)
9.1045 + throw new IllegalArgumentException(SELF_SUPPRESSION_MESSAGE);
9.1046 +
9.1047 + if (exception == null)
9.1048 + throw new NullPointerException(NULL_CAUSE_MESSAGE);
9.1049 +
9.1050 + if (suppressedExceptions == null) // Suppressed exceptions not recorded
9.1051 + return;
9.1052 +
9.1053 + if (suppressedExceptions == SUPPRESSED_SENTINEL)
9.1054 + suppressedExceptions = new ArrayList<>(1);
9.1055 +
9.1056 + suppressedExceptions.add(exception);
9.1057 + }
9.1058 +
9.1059 + private static final Throwable[] EMPTY_THROWABLE_ARRAY = new Throwable[0];
9.1060 +
9.1061 + /**
9.1062 + * Returns an array containing all of the exceptions that were
9.1063 + * suppressed, typically by the {@code try}-with-resources
9.1064 + * statement, in order to deliver this exception.
9.1065 + *
9.1066 + * If no exceptions were suppressed or {@linkplain
9.1067 + * #Throwable(String, Throwable, boolean, boolean) suppression is
9.1068 + * disabled}, an empty array is returned. This method is
9.1069 + * thread-safe. Writes to the returned array do not affect future
9.1070 + * calls to this method.
9.1071 + *
9.1072 + * @return an array containing all of the exceptions that were
9.1073 + * suppressed to deliver this exception.
9.1074 + * @since 1.7
9.1075 + */
9.1076 + public final synchronized Throwable[] getSuppressed() {
9.1077 + if (suppressedExceptions == SUPPRESSED_SENTINEL ||
9.1078 + suppressedExceptions == null)
9.1079 + return EMPTY_THROWABLE_ARRAY;
9.1080 + else
9.1081 + return suppressedExceptions.toArray(EMPTY_THROWABLE_ARRAY);
9.1082 + }
9.1083 +}
10.1 --- a/pom.xml Fri Sep 28 14:58:21 2012 +0200
10.2 +++ b/pom.xml Fri Sep 28 17:59:03 2012 +0200
10.3 @@ -9,6 +9,7 @@
10.4 <modules>
10.5 <module>vm</module>
10.6 <module>htmlpage</module>
10.7 + <module>emul</module>
10.8 </modules>
10.9 <licenses>
10.10 <license>