2015-02-10 31 views
1

我知道String是不可變的。但是,由於這個原因,我不明白爲什麼下面的代碼可以工作(來自Oracle的代碼示例)。我指的是「path = path.replace(sep,'/');」有人可以幫忙解釋嗎?Java中的不可變字符串 - 替換方法的作品?

import oracle.xml.parser.v2.*; 

import java.net.*; 
import java.io.*; 
import org.w3c.dom.*; 
import java.util.*; 

public class XSDSample 
{ 
    public static void main(String[] args) throws Exception 
    { 
     if (args.length != 1) 
     { 
     System.out.println("Usage: java XSDSample <filename>"); 
     return; 
     } 
     process (args[0]); 
    } 

    public static void process (String xmlURI) throws Exception 
    { 

     DOMParser dp = new DOMParser(); 
     URL  url = createURL (xmlURI); 

     // Set Schema Validation to true 
     dp.setValidationMode(XMLParser.SCHEMA_VALIDATION); 
     dp.setPreserveWhitespace (true); 

     dp.setErrorStream (System.out); 

     try 
     { 
     System.out.println("Parsing "+xmlURI); 
     dp.parse (url); 
     System.out.println("The input file <"+xmlURI+"> parsed without 
errors"); 
     } 
     catch (XMLParseException pe) 
     { 
     System.out.println("Parser Exception: " + pe.getMessage()); 
     } 
     catch (Exception e) 
     { 
     System.out.println("NonParserException: " + e.getMessage()); 
     } 

    } 

    // Helper method to create a URL from a file name 
    static URL createURL(String fileName) 
    { 
     URL url = null; 
     try 
     { 
     url = new URL(fileName); 
     } 
     catch (MalformedURLException ex) 
     { 
     File f = new File(fileName); 
     try 
     { 
      String path = f.getAbsolutePath(); 
      // This is a bunch of weird code that is required to 
      // make a valid URL on the Windows platform, due 
      // to inconsistencies in what getAbsolutePath returns. 
      String fs = System.getProperty("file.separator"); 
      if (fs.length() == 1) 
      { 
       char sep = fs.charAt(0); 
       if (sep != '/') 
        path = path.replace(sep, '/'); 
       if (path.charAt(0) != '/') 
        path = '/' + path; 
      } 
      path = "file://" + path; 
      url = new URL(path); 
     } 
     catch (MalformedURLException e) 
     { 
      System.out.println("Cannot create url for: " + fileName); 
      System.exit(0); 
     } 
     } 
     return url; 
    } 

} 

回答

4

path = path.replace(sep, '/');創建一個新的String實例,並將其分配給path變量。由path引用的原始String未更改,因爲如您所知,字符串是不可變的。

如果您要撥打path.replace(sep, '/')而未將結果指定給path,則path將繼續引用原始String

0

該字符串本身未被修改。然後,處理程序path指向一個新的字符串,它是以前的值path,並進行了一些替換。

0

字符串實例總是不可變

簡單的例子:

public static void main(String[] args) throws IOException { 
    String s = "abc"; 
    String replacedString = s.replace("a", "x"); // returns a "new" string after replacing. 
    System.out.println(s == replacedString); // false 
}