generics - Homework help, Java Pair class -


i have homework assignment compare generic pair have created in class , send tester class comparison , should return true. can't figure out i'm doing wrong. think may equals method when trying compare 2 objects. when think on right track stackoverflow exceptions. here portion of code:

import java.util.arraylist;  public class pair<t1,t2> implements pairinterface<t1,t2> {     private t1 afirst;     private t2 asecond;     pair p1 = new pair(afirst,asecond);      public pair(t1 afirst, t2 asecond)     {              this.afirst = afirst;             this.asecond = asecond;      }      /**      * gets first element of pair.      * @return first element of pair.      */     public t1 fst()     {         return afirst;     }      /**      * gets second element of pair.      * @return second element of pair.      */     public t2 snd()     {         return asecond;     }      /**      * sets first element afirst.      * @param afirst  new first element      */     public void setfst(t1 afirst)     {         this.afirst = afirst;     }      /**      * sets second element asecond.      * @param asecond  new second element      */     public void setsnd(t2 asecond)     {         this.asecond = asecond;     }      /**      * checks whether 2 pairs equal. note pair      * (a,b) equal pair (x,y) if , if      * equal x , b equal y.      * @return true if pair equal apair. otherwise      * return false.      */         @override     public boolean equals(object otherobject)     {          pair p2 = (pair) otherobject;          if(otherobject == null)         {             return false;         }          if(getclass() != otherobject.getclass())         {             return false;         }                 if(p1.equals(p2)){                     return true;                 }else{                     return false;                 }            }        /**      * generates string representing pair. note      * string representing pair (x,y) "(x,y)". there      * no whitespace unless x or y or both contain whitespace      * themselves.      * @return string representing pair.      */         @override     public string tostring()     {         return new stringbuilder().append('(').append(fst()).append(',').append(snd()).appen         d(')').tostring();     } } 

at first, why creating new instance of class?

pair p1 = new pair(afirst,asecond); 

you should'n this, when object created using constructor, fields initialized.

second, have recursive problem in equals method, calls equals inside itself.

you've got change equals method

pair p2 = (pair) otherobject;        if (otherobject == null) {          return false;       }        if (this == otherobject) {          return true;       }        if (getclass() != otherobject.getclass()) {          return false;       }        return this.afirst.equals(p2.afirst)             && this.asecond.equals(p2.asecond); 

Comments