簡體   English   中英

Java內置方法的邏輯

[英]logic of java in-built method

誰能告訴我,在哪里可以找到java內置String方法的邏輯,例如length()tocharArray()charAt()等...我曾嘗試對String.class反編譯,但沒有發現它們的邏輯。 我想一個代碼來計算一個字符串的字符數,而無需使用任何內置的String類,但我無法破解如何突破成字符串的字符集,而無需使用字符串內置方法的想法..如String str = "hello"; 如何將此字符串轉換為

'h' ,  'e' ,  'l' , 'l' , 'o' 

這不是任何家庭作業...

請幫忙問候,希曼書

JDK提供了內置庫源代碼。

JDK文件夾將包含src.zip ,其中包含內置庫的源。

在此處輸入圖片說明

在此處輸入圖片說明

我一直使用http://grepcode.com 它通常具有我要查找的方法/對象的源代碼。 這是String類String.length()的 GC

編輯:至於第二個問題,如何計算字符串長度。 我會使用String.toCharArray()。 我希望您可以計算數組的長度。

整個字符串數據都保存在私有char array字段中。

length()只是:

  public int length()
  {
       return this.value.length;
  }

而且charAt(int)並不復雜:

public char charAt(int paramInt)
{
    if ((paramInt < 0) || (paramInt >= this.value.length)) {
      throw new StringIndexOutOfBoundsException(paramInt);
    }
    return this.value[paramInt];
}

您正在尋找分離字符串字符的方法是toCharArray()

如果要反編譯.class文件,請嘗試使用: http ://jd.benow.ca/它具有GUI應用程序和Eclipse IDE插件。

您可以在線查看OpenJDK源代碼。 確保您正在查看正確的代碼版本(庫版本和修訂版)。

例如,這是toCharArray()的代碼:

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

這是charAt(int index)

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

您可以在這里找到String類的源代碼。

如果不直接或間接使用String無法使用它。 例如,您可以使用charAt(int index)遍歷字符串字符,或創建一個StringBuilder(String s) (內部調用String.length() )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM