//This code show you how to make set of obecjts , so just do this for a3,a4 as well.
Set<Abilities> a1 = new HashSet<Abilities>();
a1.add(new Abilities("sing"));
a1.add(new Abilities("dance"));
a1.add(new Abilities("shoot"));
Set<Abilities> a2 = new HashSet<Abilities>();
a2.add(new Abilities("sing"));
a2.add(new Abilities("dance"));
a2.add(new Abilities("shoot"));
//You should remember to change from array of abilities to set in the definition of your Person class.
Person p1 = new Person(a1);
Person p2 = new Person(a2);
Set<Person> persons = new HashSet<Person>();
persons.add(p1);
persons.add(p2);
we will use iterator with set here.
Person temp = null;
Iterator<Person> iterator = persons.iterator();
while(iterator.hasNext(){
Person tempPerson = iterator.next();
for(Person p : persons){ //This for loop will compare with all other objects
if(p!=tempPerson){
if(compareSets(tempPerson.getAbilities(),p.getAbilities())){
throw new SameAbilitiesException("Persons with same abilities");
}
}
}
}
The Method which you can use to check if two sets are the same.
//check whether set2 contains all elements of set1
private static boolean compareSets(Set<Abilities> set1, Set<Abilities> set2) {
if(set1.isEmpty() || set2.isEmpty()) {
return false;
}
return set2.containsAll(set1);
}
if you want to keep your code with Array :
Person temp = null;
for(int i = 0; i < Person.length; i++)
{
// Here it will be array of type Abilites not Person
Abilities[] tmp = persons[i].getAbilities();
//This for loop will start from first index to compare
for(int j=0; j<Person.length;j++){
if(i!=j){ // This if because we don't want to compare same array with it's self
if (Arrays.equals(Person[i].getAbilities(), tmp))
throw new SameAbilitiesException("Persons with same abilities exception!");
}
}
}
CLICK HERE to find out more related problems solutions.