Reputation: 59
I have an array list with four object elements in it and i need to compare these objects with each other. I need to avoid the similar object comparisons and doing a continue in case if both objects are same. I have tried the below code but it's avoiding the common object iterations. Can anyone suggest me a best way to compare the elements in the same Array list?
Code:
List<Student> studentInfo= new ArrayList<Student>();
for (int i = 0; i < list.size(); i++)
{
for (int j = 0 ; j < list.size(); j++)
{
if(list.get(i).getstudentId().equals(list.get(j).getstudentId()))
continue;
}
}
}
Upvotes: 0
Views: 2868
Reputation: 279
You can use the bubble sort algorithm but instead of sort, you could use it for your needs.
A more elegant method to compare would be:
public class Student {
private String id;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals (Object otherObject){
if(!(otherObject instanceof Student)){
return false;
}
if(((Student)otherObject).getId().equals(this.id)){
return true;
}
return false;
}
}
In your class:
for(int i = 0; i< studentList.size(); i++){
for(int j = i+1; j< studentList.size(); j++){
if(studentList.get(i).equals(studentList.get(j))){
continue;
}
}
}
Upvotes: 0
Reputation: 14383
you need to avoid the case where i == j in which case your if will evaluate to true
if(i != j && list.get(i).getstudentId().equals(list.get(j).getstudentId()))
break;
if you want to know at the exit of the loop if you found a duplicate, you need an external variable to let you know (like boolean or perhaps an int that will show where the duplicate was found)
Upvotes: 3