简体   繁体   中英

equals() not working as expected

I'm trying to compare two post data fields to see if they're the same. If they're different I'm going to save the info. However I can't seem to get equals() to work correctly. Here's a sample:

String oldDesc1 = request.getParameter("desc1_old");
String oldDesc2 = request.getParameter("desc2_old");
String desc1 = request.getParameter("desc1");
String desc2 = request.getParameter("desc2");

if (!oldDesc1.equals(desc1) || !oldDesc2.equals(desc2)) {
    out.println("made it!!");
    part.setDescription(new String[] {desc1, desc2});
}
//added for testing
out.println("Old Desc 1: "+oldDesc1);
out.println("New Desc 1: "+desc1);
out.println("Old Desc 2: "+oldDesc2);
out.println("New Desc 2: "+desc2);

Now my Servlets output looks like this:

Old Desc1: foo1
New Desc1: bar1
Old Desc2: foo2
New Desc2: bar2

Notice how it's missing the "made it!!"

===EDIT====

My goal is to check and if either desc1 changes, desc2 changes, or both change to write the new info. Given the answers I'm seeing, you're statements are saying if desc1 and desc2 changes then save the info. I'm sorry if I didn't explain myself clearly enough before!

You should refer to De morgan's laws :

(not a) OR (not b)  ⟷  not (a AND b)

Applying this rule to your condition, it'll be equivalent to:

if (!(oldDesc1.equals(desc1) && oldDesc2.equals(desc2)))

which is not what you want, use && instead of || .

if (!oldDesc1.equals(desc1) || !oldDesc2.equals(desc2)) {
    out.println("made it!!");
    part.setDescription(new String[] {desc1, desc2});
}

you are using || (OR) instead of && (AND) operator.

Modified code:

if (!oldDesc1.equals(desc1) && !oldDesc2.equals(desc2)) {
    out.println("made it!!");
    part.setDescription(new String[] {desc1, desc2});
}

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