Java输入来自终端的奇怪行为

Zen*_*ser 1 java shell command-line args

我有以下代码,除了命令行参数,每次我写"Insertion"它不会进入if语句所以输出将是"Algorithm not found. Use: [ Insertion | Merge ]"

  public static void main(String[] args) throws IOException, InsertionAndMergeException, Exception {
    if( args.length < 2 ) {
      System.out.println("Use: <path> <algorithm> ");
      System.exit(1);
    }

    if(args[1] == "Insertion" || args[1] == "Merge"){

      testWithComparisonFunction(args[0], args[1], new RecordComparatorIntField());

    }else
      System.out.println("Algorithm not found. Use: [ Insertion | Merge ]");
  }  
Run Code Online (Sandbox Code Playgroud)

在命令行中我打字这个,我做错了什么?

java insertionandmergeusagejava/InsertionAndMer
geUsage "/home/zenoraiser/Scrivania/Università/Secondo Anno/Algoritmi/1718/LAB/Progetto/Integers.txt" "Insertion"
Run Code Online (Sandbox Code Playgroud)

A. *_*ock 5

你混淆==.equals,如果你改变你的if语句

if ("Insertion".equals(args[1]) || "Merge".equals(args[1])) {
Run Code Online (Sandbox Code Playgroud)

你应该得到预期的结果.

在Java中,==操作需要的LHS值并直接与RHS值进行比较,这是好的基本类型如int,double等字符串是有些不同.因为String实际上是一个字符数组,所以它存储为a Object,因此==运算符将比较指向 LHS/RHS 的指针(在这种情况下不相等).

您可以使用以下代码观察看似奇怪的行为:

String a = "Test.";
String b = "Test.";
System.out.println(a == b); // true
System.out.println(a.toLowerCase() == b.toLowerCase()); // false
Run Code Online (Sandbox Code Playgroud)

这是由于一个称为"字符串实习"的过程,它有效地在同一个指针下存储多个字符串,同时它们具有相同的值.

另请注意,通过在比较中首先放置字符串文字,可以消除NullPointerExceptionif args[1]不存在的可能性.