java中的String类中的使用问题

作者在 2021-01-16 15:13:30 发布以下内容
package String;

public class Test01 {

    public static void main(String[] args) {
        //String 是一个类,创建一个对象后,该对象会有变量方法等,
        //不要把String当成一个普通变量来比较"=="这个符号
        //String 对hashCode方法进行了重写;得到的是字符串的编码而和别的类要区别对待
        {
        String a="hello word";//由String 创建的a指向堆内存的空间
        String b="hello word";//由String 创建的b指向堆内存的空间和a指向的空间一样
        System.out.println(a.hashCode());//hashCode字符串的编码,如果相同这代表字符串相等
        System.out.println(b.hashCode());
        
        
        
        System.out.println(a==b);//结果为true 这个时候判断相等是比较地址是否相等
        System.out.println("-----------");
        }
        {
        String c=new String("hello word");//new 引用一个任意的空间;
        String d=new String("hello word");
        System.out.println(c.hashCode());
        System.out.println(d.hashCode());
        System.out.println(c==d);//这个时候发现结果是false,c和d指向的不是一个空间
        //如果c和d的hashCode相同但hashCode不是地址“对象地址是否相等可以用c==d判断”
        System.out.println("-----------");
        }
        {
            //如果要比较对象中的具体值是否相等,可以用
            
            String a="hello word";
            String b="hello word1";
            System.out.println(a.equals("b"));//判断是否相等
            System.out.println(a.valueOf(b));//赋值
            System.out.println("----------");
            
        }
        {
            String a="hello word";
            String b=new String("hello word");
            //hashCode字符串的编码,如果相同这代表字符串相等
            System.out.println(a.hashCode());
            System.out.println(b.hashCode());
            //输出结果hashCode相等
            
    
            
            
        }
        
        
        
        
        
        
        
    }

}

java | 阅读 1324 次
文章评论,共1条
topbest(作者)
2021-01-16 15:13
1
恩宇是我的小迷妹
游客请输入验证码
浏览3261次
文章分类
文章归档