How to generate identification number based on Contain?
Code:
Output:
Code:
package com.codingatharva;
class Student
{
int sid ;
String sname;
Student( int sid , String sname ) // Parameterized Constructor
{
this.sid = sid;
this.sname = sname;
}
/* Override toString() to print contain of object not address */
@Override
public String toString()
{
return sid+"...."+sname;
}
/* Override hashCode() to check memory based upon contain */
@Override
public int hashCode()
{
return sid+sname.hashCode();
}
/* Override equals method to check equality based upon contain rather
than object memory identification number */
@Override
public boolean equals( Object o )
{
Student s = (Student )o;
if( this.sid == s.sid && this.sname.equals(s.sname) )
{
return true;
}
else
{
return false;
}
}
public static void main(String args[] )
{
Student s1 = new Student( 101 , "Atharva Agrawal" );
Student s2 = new Student( 102 , "Coding Atharva" );
System.out.println(" s1: "+s1+".."+s1.hashCode()+"\t"+System.identityHashCode(s1) );
System.out.println(" s2: "+s2+".."+s2.hashCode()+"\t"+System.identityHashCode(s2) );
Student s3 = new Student( 101 , "Atharva Agrawal" );
System.out.println(" s3: "+s3+".."+s3.hashCode()+"\t"+System.identityHashCode(s3) );
System.out.println("s1 and s2: " + s1.equals(s2) );
System.out.println("s1 and s3: "+ s1.equals(s3) );
}
}
class Student
{
int sid ;
String sname;
Student( int sid , String sname ) // Parameterized Constructor
{
this.sid = sid;
this.sname = sname;
}
/* Override toString() to print contain of object not address */
@Override
public String toString()
{
return sid+"...."+sname;
}
/* Override hashCode() to check memory based upon contain */
@Override
public int hashCode()
{
return sid+sname.hashCode();
}
/* Override equals method to check equality based upon contain rather
than object memory identification number */
@Override
public boolean equals( Object o )
{
Student s = (Student )o;
if( this.sid == s.sid && this.sname.equals(s.sname) )
{
return true;
}
else
{
return false;
}
}
public static void main(String args[] )
{
Student s1 = new Student( 101 , "Atharva Agrawal" );
Student s2 = new Student( 102 , "Coding Atharva" );
System.out.println(" s1: "+s1+".."+s1.hashCode()+"\t"+System.identityHashCode(s1) );
System.out.println(" s2: "+s2+".."+s2.hashCode()+"\t"+System.identityHashCode(s2) );
Student s3 = new Student( 101 , "Atharva Agrawal" );
System.out.println(" s3: "+s3+".."+s3.hashCode()+"\t"+System.identityHashCode(s3) );
System.out.println("s1 and s2: " + s1.equals(s2) );
System.out.println("s1 and s3: "+ s1.equals(s3) );
}
}
Output: