You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中if语句比较变量值无法使用.equals()的问题

How to Compare Private position Fields Between Two Instances

Hey there! Let's work through this together—since you're new to formal programming, this is a totally common gotcha with private fields and object comparisons, so don't stress.

First, let's recap the problem to make sure I'm on the same page: you've got two instances of a class with a private position field, you wrote getter methods (like getPosition()) to access the field, but:

  • Using = just assigns values (not a comparison)
  • Using == compares object memory addresses instead of the position value
  • Calling .equals() either throws an error or doesn't give the right result
  • You can't make position public per your assignment rules

Here are two straightforward solutions that fit your constraints:

Solution 1: Compare the Values Returned by Your Getter Methods

This is the simplest approach for one-off comparisons. Since your getter method returns the actual value of the private position field, you just need to compare those returned values directly.

If position is a primitive type (like int, double, etc.)

Use == to compare the primitive values—this works because primitives are compared by their actual numeric value, not memory address:

// Assume your instances are named obj1 and obj2
if (obj1.getPosition() == obj2.getPosition()) {
    // Do something when positions are equal
}

If position is a wrapper class (like Integer, Double, etc.)

Avoid using == here (it might work for small numbers but fails for larger values because it compares object references). Instead, use the .equals() method on the wrapper objects:

if (obj1.getPosition().equals(obj2.getPosition())) {
    // Do something when positions are equal
}

Solution 2: Override equals() (and hashCode()) in Your Class

If you need to compare instances frequently (not just their position field), you can override the default equals() method in your class. Since you're writing code inside the class itself, you can directly access the private position field without making it public—perfect for your assignment rules.

Here's how to implement it:

import java.util.Objects;

public class YourClassName {
    private int position; // Or whatever type your position is

    // Your existing constructor, getter, etc.
    public int getPosition() {
        return position;
    }

    @Override
    public boolean equals(Object o) {
        // 1. Check if we're comparing the exact same object
        if (this == o) return true;
        // 2. Check if the other object is null or a different class
        if (o == null || getClass() != o.getClass()) return false;
        // 3. Cast to your class type
        YourClassName that = (YourClassName) o;
        // 4. Compare the private position fields directly
        return position == that.position;
    }

    // Always override hashCode() when you override equals()—this keeps them consistent
    @Override
    public int hashCode() {
        return Objects.hash(position);
    }
}

Now you can compare instances directly with .equals():

if (obj1.equals(obj2)) {
    // This will be true if their position fields are equal
}

Why Your Earlier .equals() Call Failed

The default equals() method (inherited from Object) only compares memory addresses, just like ==. If you didn't override it, calling obj1.equals(obj2) would only return true if they're the exact same object in memory—not if their position values match. If you got an error, you might have accidentally passed a non-object to .equals() (like trying to compare an instance to a getPosition() value directly), which would cause a type mismatch.

Either of these solutions will work within your assignment's rules—pick the one that makes the most sense for how often you need to compare these instances!

内容的提问来源于stack exchange,提问作者Jaffar Rizvi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:58:24