相关疑难解决方法(0)

如何比较Java中的字符串?

==到目前为止,我一直在我的程序中使用运算符来比较我的所有字符串.但是,我遇到了一个错误,将其中一个更改为了.equals(),并修复了该错误.

==坏?什么时候应该不应该使用它?有什么不同?

java string equality

726
推荐指数
23
解决办法
376万
查看次数

String.equals与==

此代码将字符串分隔为标记并将它们存储在字符串数组中,然后将变量与第一个主页进行比较...为什么它不起作用?

public static void main(String...aArguments) throws IOException {

    String usuario = "Jorman";
    String password = "14988611";

    String strDatos = "Jorman 14988611";
    StringTokenizer tokens = new StringTokenizer(strDatos, " ");
    int nDatos = tokens.countTokens();
    String[] datos = new String[nDatos];
    int i = 0;

    while (tokens.hasMoreTokens()) {
        String str = tokens.nextToken();
        datos[i] = str;
        i++;
    }

    //System.out.println (usuario);

    if ((datos[0] == usuario)) {
        System.out.println("WORKING");
    }
}
Run Code Online (Sandbox Code Playgroud)

java string

515
推荐指数
16
解决办法
80万
查看次数

在Java中连接字符串是否总会导致在内存中创建新字符串?

我有一个不符合屏幕宽度的长字符串.例如.

String longString = "This string is very long. It does not fit the width of the screen. So you have to scroll horizontally to read the whole string. This is very inconvenient indeed.";
Run Code Online (Sandbox Code Playgroud)

为了便于阅读,我想到了这样写 -

String longString = "This string is very long." + 
                    "It does not fit the width of the screen." +
                    "So you have to scroll horizontally" +
                    "to read the whole string." +
                    "This is very inconvenient indeed.";
Run Code Online (Sandbox Code Playgroud)

但是,我意识到第二种方式使用字符串连接,并将在内存中创建5个新字符串,这可能会导致性能下降.是这样的吗?或者编译器是否足够智能,以确定我需要的只是一个字符串?我怎么能避免这样做?

java compiler-construction string string-concatenation

24
推荐指数
2
解决办法
5320
查看次数

Java 字符串池是否存储重复的文字?

正如我所理解的,每当我们创建一个String文字时,都会检查池中是否存在String具有相同值的任何现有内容。如果存在,则返回对其的引用。否则会创建一个新的文字。

由此,我明白池只包含非重复的String文字。

但我对以下代码的输出感到困惑:

String str1 = "Hello World";
String str2 = "Hello";
String str3 = str2+" World";
System.out.println(str3);
System.out.println(((str1 == str3) ? "equal":"unequal"));`
Run Code Online (Sandbox Code Playgroud)

由于str3正在评估 指向"Hello World"的池中已经存在的对象,因此应该str1分配对相同对象的引用str3,因此str1并且str3应该是相等的。

但是代码显示它们是不平等的。如果有人可以解释,将不胜感激。

java string

1
推荐指数
1
解决办法
65
查看次数