-2

In my project I use employee bean list in the list empVal string value contain 01,02,03,05 in the same I need to avoid in another string

i.e in first bean emp1.empval="01,02,03,05" and second bean emp2.empval=" 01,02,03,05". So emp2.empval should not be allowed as bean value numbers are present in emp2. empval is already exists in emp1.empval.

pulblic class employee
{
  private String empVal;
  ......
}

my doubt is how to achieve it either using iterate or split to compare string or any other way is possible?

Veeresh123
  • 87
  • 16

2 Answers2

1

You can override the equals method and check

 @Override
public boolean equals(Object obj) {
    if(obj instanceof employee){
        employee emp= (employee) obj;
        if(this.empVal.equals(emp.empVal){
            return true;
        }
    }
    return false;
}

and then before adding the elements you can check, also you can add the other variables you have declared in you class if(emp!= null && this.empVal.equals(emp.empVal) && this.empVal1.equals(emp.empVal1))

For eg:
ArrayList<employee> empList= new ArrayList<employee> (); employee emp1 = new employee ("a"); employee emp2 = new employee ("b"); employee emp3 = new employee ("b"); empList.add(emp1); empList.add(emp2); if(empList.contains(emp3)) { System.out.println("Yes"); } else { System.out.println("No"); empList.add(emp3); //Adding if that object is not present in the list. }

Basically contains method will check if the object is present by internally calling the equals method.

For more information on contains functionality you can check the link How does a ArrayList's contains() method evaluate objects?

Community
  • 1
  • 1
Rishal
  • 1,480
  • 1
  • 11
  • 19
0

Hi you can achive this by

 Boolean valueExists = emp1.empVal.equals(emp2.empVal);
Veeresh123
  • 87
  • 16