简体   繁体   中英

Java foreach loop not finding existing list element

I am looping through a collection of Parameter objects, looking for Parameter.name = "Code" . If I can't find it I default to the first Parameter in the list, as below:

    header = WBMessageFactory.getWBMessageDescriptor(Configuration.getWBHeaderIDString());

    for (Parameter p : header.getSegment().getParameter()) {
        if (p.getName() == "Code") {
            String wbCode = raw.substring(p.getStartPosition().intValue(), p.getLength().intValue());
            logger.info("Found WB code... " + wbCode);
            body = WBMessageFactory.getWBMessageDescriptor(wbCode);
            break;  
        }
    }

    if (body == null) {
        Parameter p = header.getSegment().getParameter().get(0);
        logger.error("Could not find Code parameter in Header template, using " + p.getName());
        body = WBMessageFactory.getWBMessageDescriptor(raw.substring(p.getStartPosition().intValue(), p.getLength().intValue()));
    }

As you can see, I log the Parameter name when I can't find Code. Occasionally , logging reveals the following:

Could not find Code parameter in Header template, using Code

Can anyone explain what the heck is going on?

The problem is here:

 if (p.getName() == "Code") {

You probably meant to say

 if (p.getName().equals("Code")) {

The first one compares the string reference , which is almost certainly not what you want. The second one compares the contents of the string.

Your problem is in the following line:

if (p.getName() == "Code")

To check for String equality you have to use equals.

You're comparing the strings with == , you should use equals() . If you intern both of the strings, you could compare them with == , but interned Strings are retained by the JVM for a long time which could be considered a memory leak, and the microoptimisation probably isn't of benefit very often.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM