Java – why does my if conditional compare string fail?

This program execution does not enter the if condition

public static void filterObject(ArrayList<treewalker.VariableNode> variableNodeslist,ArrayList<treewalker.ObjectNode> objectNodeslist,ArrayList<treewalker.ClassNode> classNodeslist) {
        int i,j;
        for (i = 0; i < variableNodeslist.size(); i++) {
            for (j = 0; j < classNodeslist.size(); j++) {
                String argu1 = variableNodeslist.get(i).typeClass.toString();
                String argu2 = classNodeslist.get(j).name.toString();
                System.out.println(argu1);
                System.out.println(argu2);
                if (argu1 == argu2)//this if loop is not getting executed 
                {
                    System.out.println("inside for");
                }
                System.out.println("hi");
            }
        }
    }@H_502_13@

Solution

Short answer:

Longer answer: the = = operator in Java performs reference comparison

If you want to make a string comparison, use:

if (argu1.equals(argu2))@H_502_13@ 
 

在某些情况下,==运算符似乎可能会进行相等性检查,例如:

String var1 = "abc";
String var2 = "abc";

String result = ("abc" == "abc");@H_502_13@ 
 

在这种情况下,结果是真的,最初看起来似乎是相等比较,但实际上是编译器优化,其中var1和var2共享相同的引用.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>