dz̸ΪʲôJavaStringDzɱ

 ʱ䣺20190314 10:34:41   ת ߣħ  
ƪҪΪʲôJavaStringDzɱģͨʾܵķdzϸԴҵѧϰ߹һIJοѧϰֵҪСһѧϰѧϰ

JavaStringDzɱһʣôΪʲôJavaԵҪStringƳɲɱأһֵ˼

JavaԵĴJames GoslingһβɷбʵʲôʱӦʹòɱimmutable objectشκοʹõʱ򶼻ʹá

֮ǰ˽һ£ʲôDzɱ

ɱָڶ󴴽֮󣬶ڲ״̬Լڴַָܱı䡣Javafinalؼ־ɱģҪעǣڻͱfinalκ󣬾ͳױ˲ɱ󣬶ͱfinalκ󣬽ָڴַܸı䣬Ҫɳ׵IJɱͣҪѸöеֶζfinalǶ׵Ķ󣬷ڲ״̬Ҳǻ仯ģһҪ⡣

okΪʲôStringDzɱģ

ͨStringԴԿString͵ĵײfinalεchar洢

public final class String
  implements java.io.Serializable, Comparable<String>, CharSequence {
  /** The value is used for character storage. */
  private final char value[];
  
  ........
  }

StringܱƳɲɱ͵һҪǰΪDZʹƵߵһ͡ɱʹĺôĸ棬ֱǣ棬ȫͬܡ

һ

JVMʱ棬һרŵַ洢ַһδ룺

String s1 = "Hello World";
String s2 = "Hello World";
     
assertThat(s1 == s2).isTrue();

s1s2ָڴַʵһģҲ˵ǴͬһjvmŻһʱֵᱻַش洢s2ʱjvmֳѾڸöԾͲٴһΣֱӽһڴָ븳ֵs2ӱظ󣬽ʡڴռ䡣

⣬ַIJɱԣӶhashCodeҲ棬JavaϣݽṹHashMap, HashTable, HashSetkeyõĻStringͣһkeyhashCodeҲڵһε֮󱻻棬ֱ֮ʹɣӶӵЧʡ

ȫ

ɱҲܹӦóʱİȫ⣬һδ룺

void criticalMethod(String userName) {
  // check
  if (!check(userName)) {
    throw new SecurityException(); 
  }
   
  // query 
  query(userName);
  
  }

һδ룬ڵ֮ȼûϷſԼѯݣStringɱ䣬ô߾Ϳͨcheck֤֮ٸıѯûôͻڰȫգɱܹͼһһ棬Stringǿɱģôͬʱе߳޸ֵпܵ»ҡ

ͬ

String͵IJɱԣʹString԰ȫڶ֮߳䴫ݺͷʣҲ˵ڶ߳Dzܸıֵַڶ´һַȻȻûfinalΣǿԸıõַҲ˵԰ɵڴøԭıããDZֵһҪע⡣

ģ

ܷ棬ʵǰѾᵽˣַijؽʡڴ棬HashַkeyݽṹhashCodeӶ߷ܵȡַDZ㷺ʹõݽṹַIJɱԴƣԷŴеӦó򣬴ӶӦó

ܽ᣺

ҪJavaStringΪʲôƳɲɱͣԼ˲ɱ͵ĴҪƣҪעȻɱܹٵĺô˵ûб׶ˣɱ͵ÿһ޸ĶҪڴһ󣬴һ˵Ծ仯ĶDzʺʹòɱ͵ģҲΪʲôJava滹ṩ˿޸ֵStringBuilderStringBuffer࣬ʵʿгҪݾȨġ

СҽܵΪʲôJavaStringDzɱϣϣԴκԣСἰʱظҵġڴҲdzлҶԽű֮վ֧֣