新的String()字符串初始化和Java中的新字符串(“&”;)有什么区别? [英] What is the difference between String initializations by new String() and new String("") in Java?

查看:120
本文介绍了新的String()字符串初始化和Java中的新字符串(“&”;)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中的以下两个初始化之间有什么区别?

What is the difference between the following two initializations in Java?


  1. 字符串a = new String() ;

  2. 字符串b =新字符串();

  1. String a = new String();
  2. String b = new String("");


推荐答案

嗯,它们几乎相同

public static void main(String[] args) {
    String s1 = new String();
    String s2 = new String(""); 
    System.out.println(s1.equals(s2)); // returns true.
}

微小差异(相当微不足道):

Minor differences (rather insignificant) :


  1. new String(); 执行的时间少于 new String( ); 因为复制构造函数做了很多事情。

  1. new String(); takes less time to execute than new String(""); because the copy constructor does a lot of stuff.

new String() 将空字符串()添加到字符串常量池(如果它尚不存在)。

new String("") adds the empty String ("") to the String constants pool if it is not already present.

除此之外,没有其他差异

Other than this, there are no other differences

注意:使用 new String(abc)几乎总是坏的,因为你将在String常量池上创建2个字符串,在堆上创建另一个具有相同值的字符串。

Note : The use of new String("abc") is almost always bad because you will be creating 2 Strings one on String constants pool and another on heap with the same value.

这篇关于新的String()字符串初始化和Java中的新字符串(“&”;)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆