从System.in读取的两个相同的字符串是否会存储在公共内存位置?

Nem*_*ric 3 java

假设我们有这样的程序:

import java.io.*;

public class ReadString {

   public static void main (String[] args) {

      //  prompt the user to enter their name
      System.out.print("Enter your name: ");

      //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String userName = null;
      String userNameCopy = null;

      //  read the username from the command-line; need to use try/catch with the
      //  readLine() method
      try {
         userName = br.readLine();
         System.out.print("Enter your name once again: ");
         userNameCopy = br.readLine();
      } catch (IOException ioe) {
         System.out.println("IO error trying to read your name!");
         System.exit(1);
      }

      System.out.println("Thanks for the name, " + userName);

   }

}  // end of ReadString class
Run Code Online (Sandbox Code Playgroud)

现在,如果用户输入自己的用户名两次,userName而且userNameCopy字符串将具有相同的价值.由于字符串是不可变的,Java编译器是否足够聪明,只能使用一个具有两个引用的内存对象,或者这种行为仅保留给硬编码到程序中的字符串文字?

如果答案是"否,编译器将在堆上创建两个单独的对象".为什么会这样?是因为从游泳池搜索完全匹配是慢的吗?如果是,那么字符串池是不是可以像某种哈希表那样实现,或类似的东西?

Pat*_*han 6

池实现为散列数据结构.Java决定是否进行搜索,并共享非文字的String对象,直到程序员.请参阅String方法intern().