简体   繁体   English

使用ID java插入列表

[英]insert into List using ID java

Currently I have a method to insert behaviors into a List from another class called Aptitude . 目前,我有一种方法可以将行为从另一个名为Aptitude的类插入到List中。 Behaviors have an ID and I want to insert the next behavior created into the list with the next available ID not present in the whole List. 行为具有ID,我想将创建的下一个行为插入到列表中,而下一个可用ID不在整个列表中。 I'm doing it like this: 我正在这样做:

public Behavior addBehavior(BehaviorDto behaviorDto, String aptitudeId) {
    Aptitude aptitude;
    aptitude = findById(aptitudeId);
    List<Behavior> behaviors = aptitude.getBehaviors();
    int nextId = -1;
    boolean flag;
    for (int i = 1; i <= behaviors.size() + 1; i++) {
        flag = true;
        for (Behavior behavior1 : behaviors) {
            if (Integer.parseInt(behavior1.getId()) == i) {
                flag = false;
                continue;
            }

        }
        if (flag) {
            nextId = i;
            break;
        }
    }

But I remember being told that there was a way to optimize and not need to use a flag variable. 但是我记得有人告诉我,有一种方法可以优化而不需要使用标志变量。

How can I improve this code? 如何改善此代码?

edit 编辑

the rest of the method: 其余方法:

Behavior behavior = new Behavior(String.valueOf(nextId), behaviorDto.getEn(), behaviorDto.getEs());
behavior.setId(String.valueOf(nextId));
aptitude.addBehavior(behavior);
updateAptitude(aptitude);
return behavior;

I would expect Aptitude to 'know' the next available behavior id (Object Oriented) . 我希望Aptitude能够“知道”下一个可用的行为ID (面向对象)

public Behavior addBehavior(BehaviorDto behaviorDto, String aptitudeId) {
    Aptitude aptitude = findById(aptitudeId);
    List<Behavior> behaviors = aptitude.getBehaviors();
    int nextId = aptitude.getNextBehaviorId()

    // ...
}

You can move id generation to Behavior's constructor: 您可以将id生成移到Behavior的构造函数中:

class Behavior {
    private static AtomicInteger counter = new AtomicInteger(0);

    public Behavior(BehaviorDto behaviorDto) {
        \\other constructor things
        this.id = counter.incrementAndGet();
    }
}

After this be done, you can just do: 完成此操作后,您可以执行以下操作:

public Behavior addBehavior(BehaviorDto behaviorDto, String aptitudeId) {
    Aptitude aptitude;
    aptitude = findById(aptitudeId);
    List<Behavior> behaviors = aptitude.getBehaviors();
    Behavior newBehavior = new Behavior(behaviorDto);
    behaviors.add(newBehavior);
    return newBehavior;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM