首页 > 解决方案 > 如何访问保存在另一组对象中的一组对象

问题描述

我有一组例如对象,其中有一组对象能力,我如何检查两个人是否具有相同的能力,换句话说,我如何访问一组中的另一组,只有我发现我需要的结果用于每个循环,但我可以为每个循环使用两个集合吗?使用数组的代码看起来像这样

Abilities[] a1 = {new Abilities("sing"), new Abilities("dance"), new Abilities("shoot")};
Abilities[] a2 = {new Abilities("fly"), new Abilities("run"), new Abilities("box")};
Abilities[] a3 = {new Abilities("dig"), new Abilities("build"), new Abilities("mine")};
Person p1 = new Person(a3);
Person[] persons = {new Person(a1), new Person(a2), new Person(a3)};
Abilities[] a4 = p1.getAbilities();

for(int i = 0; i < persons.lenght; i++) 
      {
           Person[] tmp = persons[i].getAbilities();
           if (Arrays.equals(a4, tmp))
               throw new SameAbilitiesException("Persons with same abilities exception!");
        }

如何使用 Abilities 和 Persons 的集合来重构它

标签: javalistset

解决方案


//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);

我们将在这里使用带有 set 的迭代器。

       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");
     }
   }  
  }
}

您可以用来检查两组是否相同的方法。

//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);
}

如果你想用 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!");
}
            }
    }

推荐阅读