gpt4 book ai didi

java - foreach 循环内的 foreach 循环 (Java)

转载 作者:行者123 更新时间:2023-12-01 14:19:26 24 4
gpt4 key购买 nike

我有以下代码:

Set<TOrganization> organizations = new LinkedHashSet<TOrganization>();
Set<TRole> roles = new LinkedHashSet<TRole>();
StringBuilder message = new StringBuilder("Requested roles: " + "\n");

//I fill them up with names like Test org A, Test Role A 1

for(TOrganization org : organizations) {
message.append(" - " + org.getName()+ "\n");
for(TRole role : roles) {
if(role.getOrganization().equals(org)) {
message.append(" - " + role.getName()+ "\n");
}
}
}

我想打印出不同类别中的角色,如下所示:

" - Test org A"
" - Test Role A 1"
" - Test Role A 2"
" - Test org B"
" - Test Role B 1"
" - Test Role B 2"

但我的代码总是在角色之前附加组织名称,如下所示:

" - Test org A"
" - Test Role A 1"
" - Test org A"
" - Test Role A 2"
" - Test org B"
" - Test Role B 1"
" - Test org B"
" - Test Role B 2"

似乎 message.append("- "+ org.getName()+ "\n"); 每当第二个循环运行时就会执行。这怎么可能?

编辑:我用 printlns 测试了它,但角色名称很好。我没有接触 equals() 或 hashcode(),我只是用 equals() 比较字符串。问题在于,组织名称被附加到属于它们的每个角色的消息中,而它们只应出现一次。

最佳答案

这正在工作

class TOrganization {

private String name;

public TOrganization(String name) {
this.name = name;
}

public String getName() {
return name;
}

@Override
public boolean equals(Object obj) {
if (obj != null && obj instanceof TOrganization) {
if (((TOrganization) obj).getName().equals(name)) {
return true;
}
}
return false;
}

@Override
public int hashCode() {
return super.hashCode();
}

}

class TRole {

private TOrganization organization;
private String name;

public TRole(TOrganization organization, String name) {
this.organization = organization;
this.name = name;
}

public TOrganization getOrganization() {
return organization;
}

public String getName() {
return name;
}

}

public static void main(String[] args) {
Set<TOrganization> organizations = new LinkedHashSet<TOrganization>();
Set<TRole> roles = new LinkedHashSet<TRole>();
StringBuilder message = new StringBuilder("Requested roles: " + "\n");

TOrganization orga = new TOrganization("Test org A");
TOrganization orgb = new TOrganization("Test org B");

organizations.add(new TOrganization("Test org A"));
organizations.add(new TOrganization("Test org B"));
roles.add(new TRole(orga, "Test Role A 1"));
roles.add(new TRole(orga, "Test Role A 2"));
roles.add(new TRole(orgb, "Test Role B 1"));
roles.add(new TRole(orgb, "Test Role B 2"));

for (TOrganization org : organizations) {
message.append(" - " + org.getName() + "\n");
for (TRole role : roles) {
if (role.getOrganization().equals(org)) {
message.append(" - " + role.getName() + "\n");
}
}
}
System.out.println(message.toString());
}

输出

Requested roles: 
- Test org A
- Test Role A 1
- Test Role A 2
- Test org B
- Test Role B 1
- Test Role B 2

你的循环正在工作,你应该修复你的类

关于java - foreach 循环内的 foreach 循环 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17749511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com