* Object class
*/
package com.jijo;
/**
* @author jijo
*
*/
public class ComparableExample implements Comparable
private String id;
private String userName;
private String password;
private String firstName;
private String lastName;
public int compareTo(ComparableExample arg0) {
if(this.userName.equals(arg0.getUserName()))
return 0;
else
return 1;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object obj) {
if(this.getUserName() != null && this.getUserName().equalsIgnoreCase(((ComparableExample )obj).getUserName())){
return true;
}
else{
return false;
}
}
@Override
public int hashCode() {
if(this.userName != null){
return this.userName.hashCode();
}else{
return 0;
}
}
}
//Main class
package com.jijo;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List
ComparableExample comp = new ComparableExample();
comp.setUserName("jijo");
comp.setFirstName("jijo");
list.add(comp);
ComparableExample comp1 = new ComparableExample();
comp1.setUserName("mathew");
comp1.setFirstName("mathew");
list.add(comp1);
ComparableExample comp2 = new ComparableExample();
comp2.setUserName("jijo");
comp2.setFirstName("jijomathew");
if(list.contains(comp2)){
System.out.println("true");//returns true
}
else{
System.out.println("false");
}
comp1 = new ComparableExample();
comp1.setUserName("jijomathew");
if(list.contains(comp1)){
System.out.println("true");
}
else{
System.out.println("false"); //returns false
}
}
}
No comments:
Post a Comment