代码改变世界

字符动手动脑

2017-10-26 22:12  Robortxin  阅读(132)  评论(0编辑  收藏  举报

动手动脑

 

 

  1. 请运行以下示例代码StringPool.java,查看其输出结果。如何解释这样的输出结果?从中你能总结出什么?

public class StringPool {

    

public static void main(String args[])

    {

        

String s0="Hello";

        

String s1="Hello";

        

String s2="He"+"llo";

        

System.out.println(s0==s1);//true

        

System.out.println(s0==s2);//true

        

System.out.println(new String("Hello")==new String("Hello"));//false

    

}

 

 

}运行结果:

 

 

使用new关键字创建字符串对象时,内容相同的字串常量只保存一份以节约内存所以s0,s1,s2实际上引用的是同一个对象在一个内存空间内

 

 

  1. 为什么会有下述的输出结果?从中你又能总结出什么?

 

 

输出结果:

 

 

给字串变量赋值意味着:两个变量(s1s2)现在引用同一个字符串对象“a

String对象的内容是只读的,使用“+”修改s1变量的值,实际上是得到了一个新的字符串对象,其内容为“ab”,它与原先s1所引用的对象”a”无关,所以,s1==s2返回false

代码中的ab”字符串是一个常量,它所引用的字符串与s1所引用的“ab”对象无关。

 

  1. 请查看String.equals()方法的实现代码,注意学习其实现方法

 

 

public class StringEquals {

 

    

/**

     * @param args the command line arguments

     */

    

public static void main(String[] args) {

        

String s1=new String("Hello");

        

String s2=new String("Hello");

 

        

System.out.println(s1==s2);

        

System.out.println(s1.equals(s2));

 

        

String s3="Hello";

        

String s4="Hello";

 

          

System.out.println(s3==s4);

        

System.out.println(s3.equals(s4));

        

    

}

 

 

}运行结果:

 

 

如果是同一个对象的引用,可知对象相等,返回true;如果不是同一个对象,equals方法挨个比较两个字符串对象内的字符,只有完全相等才返回true,否则返回false

 

4.请阅读JDKString类上述方法的源码,模仿其编程方式,编写一个MyCounter类,它的方法也支持上述的“级联”调用特性,其调用示例为:

MyCounter counter1=new MyCounter(1);

MyCounter counter2=counter1.increase(100).decrease(2).increase(3);

.

public class MyCounter

 

{

 

    int i;

 

    public MyCounter(int i)//构造方法

 

    {

 

       this.i=i;

 

    }

 

    public MyCounter()//空构造方法

 

    {

 

   

 

    }

    public MyCounter increase(int d)

 

    {

 

       MyCounter a=new MyCounter();

 

       a.i=i+d;

 

       return a;

 

    }

 

    public MyCounter decrease(int d)// 实现data减的方法,并返回对象

 

    {

 

       MyCounter a=new MyCounter();

 

       a.i=i-d;

 

       return a;

 

    }

 

    public static void main(String[] args)

 

    {

 

       MyCounter counter1=new MyCounter(1);//创建对象counter1

 

       MyCounter counter2=counter1.increase(100).decrease(2).increase(3);

 

       System.out.println(counter2.i);

 

    }

 

}

 

 

 

整理String类的Length()charAt()getChars()replace()toUpperCase()toLowerCase()trim()toCharArray()使用说明、阅读笔记

 

 

length()  返回字符串的长度

charAt ()   例:char ch;ch="abc".charAt(1); 返回'b'搜索返回所指定的字符

getChars()void getChars(int sourceStart,int sourceEnd,char target[],int targetStart)sourceStart指定了子串开始字符的下标,sourceEnd指定了子串结束后的下一个字符的下标。因此, 子串包含从sourceStartsourceEnd-1的字符。接收字符的数组由target指定,target中开始复制子串的下标值是targetStart。将字符从此字符串复制到目标字符数组

replace() (char aa ,char bb)  aabb替代

toUpperCase() 将字符串内的字符改写成大写

toLowerCase()将字符串内的字符改写成小写

trim() String x=ax  c;System.out.println(x.trim());/是去两边空格的方法

toCharArray()将字符串转换成字符数组