Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Comparing class objects

  1. Aug 16, 2011 #1

    I have a class, say myclass and it takes two strings (let s and g ) and one int ( say i) as its arguments.

    It looks like, public class {

    String s , g;
    int i ;

    public void myclass(String sname, String gname, int k){

    s = sname;
    g = gname;
    i = k;

    Now, I have several objects of this class with different values of s, g and i. I want to compare them for equality. i.e if two class objects have same s g and i value, then i want true as my output.

    I know this can be done by a loop but is there any shorter way to do this?
  2. jcsd
  3. Aug 16, 2011 #2


    User Avatar
    Gold Member

    I'm pretty sure object equality has to be done manually by overriding the equality operator and comparing each field of the two objects.
  4. Aug 17, 2011 #3


    Staff: Mentor

    A loop isn't appropriate at all. There is no way you can write a loop that will compare two strings and an int in one class instance with variables of the same types in another class instance. You will need to do a comparison in the way that DavidSnider suggests.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook