访问 pat abc 文件路径 .net copy itl near
- public final class String implements java.io.Serializable,
- Comparable < String > ,
- CharSequence {
- /** The value is used for character storage. */
- private final char value[];
- private int hash; // Default to 0
- public String() { //无参构造器
- this.value = new char[0];
- }
- public String(String original) {
- this.value = original.value;
- this.hash = original.hash;
- }
- /*****传入一个字符数组的构造函数,使用java.utils包中的Arrays类复制******/
- public String(char value[]) {
- this.value = Arrays.copyOf(value, value.length);
- }
- /*******传入一个字符串数字,和开始元素,元素个数的构造函数******/
- public String(char value[], int offset, int count) {
- if (offset < 0) {
- throw new StringIndexOutOfBoundsException(offset);
- }
- if (count < 0) {
- throw new StringIndexOutOfBoundsException(count);
- }
- // Note: offset or count might be near -1>>>1.
- if (offset > value.length - count) {
- throw new StringIndexOutOfBoundsException(offset + count);
- }
- this.value = Arrays.copyOfRange(value, offset, offset + count);
- }
- /*********************类似方法不介绍了**************************/
- public String(StringBuffer buffer) {
- synchronized(buffer) {
- this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
- }
- }
- public boolean equals(Object anObject) {
- if (this == anObject) {
- return true;
- }
- if (anObject instanceof String) {
- String anotherString = (String) anObject;
- int n = value.length;
- if (n == anotherString.value.length) {
- char v1[] = value;
- char v2[] = anotherString.value;
- int i = 0;
- while (n--!=0) {
- if (v1[i] != v2[i]) return false;
- i++;
- }
- return true;
- }
- }
- return false;
- }
- /***********s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]*********/
- public int hashCode() {
- int h = hash;
- /***如果hash没有被计算过,并且字符串不为空,则进行hashCode计算*****/
- if (h == 0 && value.length > 0) {
- char val[] = value;
- for (int i = 0; i < value.length; i++) {
- h = 31 * h + val[i];
- }
- hash = h;
- }
- return h;
- }
- /***intern方法是Native调用,它的作用是在方法区中的常量池里通过equals方法寻找等值的对象,如果没有找到则在常量池中
- 开辟一片空间存放字符串并返回该对应String的引用,否则直接返回常量池中已存在String对象的引用。*****/
- public native String intern();
举例:
- String a = "abc";
- String b = new String("ab1").intern();
- if ( a == b ) {
- System.out.println("a == b");
- } else {
- System.out.println("a不等于b");
- }
- 打印出:a == b
所谓不可变类,就是创建该类的实例后,该实例的属性是不可改变的,Java 提供的包装类和 java.lang.String 类都是不可变类。当创建它们的实例后,其实例的属性是不可改变的。
需要注意的是,对于如下代码
- String s = "abc";
- s = "def";
你可能会感到疑惑,不是说 String 是不可变类吗,这怎么可以改变呢,平常我也是这样用的啊。请注意,s 是字符串对象的 "abc" 引用,即引用是可以变化的,跟对象实例的属性变化没有什么关系,这点请注意区分。
3. 如何实现一个不可变类
既然不可变类有这么多优势,那么我们借鉴 String 类的设计,自己实现一个不可变类。
不可变类的设计通常要遵循以下几个原则:
java.lang(String)
来源: http://www.bubuko.com/infodetail-2280258.html