java - 如何访问保存在另一组对象中的一组对象
问题描述
我有一组例如对象,其中有一组对象能力,我如何检查两个人是否具有相同的能力,换句话说,我如何访问一组中的另一组,只有我发现我需要的结果用于每个循环,但我可以为每个循环使用两个集合吗?使用数组的代码看起来像这样
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 的集合来重构它
解决方案
//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!");
}
}
}
推荐阅读
- mysql - 如何通过消除将时间转换为mysql中的数字:?
- php - cURL 填写网络表单 | 跨域请求被阻止 | 第三方网站
- python-2.7 - 如何实现 GUI Less Oauth 身份验证系统以访问使用 Python-Flask 构建的 API
- jquery - 为什么我返回 renderEvents undefined (fullcalendar) 的错误
- vue.js - 如何在 vuex 商店中设置嵌套状态?
- python - ValueError:解包的值太多 4
- batch-file - 带字符串迭代的批处理 FOR 循环
- python - Django-fsm:由于额外的方法参数,动态目标失败
- selenium-webdriver - 无法在 Appium 中执行操作,因为未识别 PageFactory
- c# - 在 Internet Explorer 11 (KB4021558) 的最新更新后出现“模式对话框出现”问题