第五節 String類,subString,equals方法

下面的主要介紹一下String類,String 類中的substring方法與equals方法

public class base03 {


    public static void main(String[] args) {
        String aString="abcdefg";
        //String類源碼:如下,String類是final修飾,表示類不能被繼承,類中所有的方法都不可重寫
        //public final class String  implements java.io.Serializable, Comparable<String>, CharSequence
        //private final char value[];//說明String 其實是一個char數組
        
        
        //此時參數2爲beginIndex,
        String bString=aString.substring(2);
        //源碼,直接調用String重載方法,endIndex爲
         /*public String substring(int beginIndex) {
            return substring(beginIndex, count);
         }*/
                
        
        System.out.println(bString);
        aString.substring(1, 5);
        
        //substring源碼  此源碼的substring方法就是aString.substring(2)中的方法
        /*public String substring(int beginIndex, int endIndex) {
            if (beginIndex < 0) {
                throw new StringIndexOutOfBoundsException(beginIndex);
            }
            if (endIndex > count) {
                throw new StringIndexOutOfBoundsException(endIndex);
            }
            if (beginIndex > endIndex) {
                throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
            }
            return ((beginIndex == 0) && (endIndex == count)) ? this :
                new String(offset + beginIndex, endIndex - beginIndex, value);
       }*/
        
        
      String iString="hello";
      String jString="hello";
      System.out.println(iString==jString);//true  這就是上一篇字符串拼接講的,證明iString和jString是同一個“hello”
      
      String mString=new String("hello");
      String nString=new String("hello");
      //因爲創建兩個對象後分配內存,mString和nString中存儲的是內存地址,由於不是同一個對象
      System.out.println(mString==nString);//false  
      System.out.println(mString.equals(nString));//true
      
      //String equals 源碼:首先比較內存地址,如果內存地址是一樣的,那麼一定相等。如果不相等,則繼續
      //判斷是否是String類型,然後進行char數組的一 一 對比
      /*  public boolean equals(Object anObject) {
            if (this == anObject) {
                return true;
            }
            if (anObject instanceof String) {
                String anotherString = (String)anObject;
                int n = count;
                if (n == anotherString.count) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = offset;
                int j = anotherString.offset;
                while (n-- != 0) {
                    if (v1[i++] != v2[j++])
                    return false;
                }
                return true;
                }
            }
            return false;
            }*/
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章