java—每次添加新磁道时递增计数器,并始终选择尚未分配的最小值(>=1)

z4bn682m  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(338)

我目前正在进行一个列车模拟项目,我有一个列表,其中保存了所有轨道:

private List<Track> tracks;

    public void addTrack(Track track) {
        this.tracks.add(track);
    }

    public void removeTrack(Track track) {
        if (!tracks.contains(track)) {
            this.tracks.remove(track);
        } else {
            Terminal.printError("track with id " + track.getId() + " doesn't exist.");
        }
    }

我想在添加每个音轨时为它分配一个id(从1开始)。此外,总是选择下一个空闲id。例如,如果分配了id 1、3、4、5,则使用下一个id 2。
e。g、 地址:
添加曲目…->编号:1
添加曲目…->编号:2
拆下履带1
添加曲目…->编号:1
我会使用一个Map,每次我添加一个新的轨道,增加一个计数器。但是,如果我删除了一个id,并添加了一个新的轨道将有“差距”。
做这件事的好方法是什么?

9q78igpj

9q78igpj1#

就像赛义夫·阿西夫在回答中提到的那样,你可以使用另一个数据结构来跟踪id。
bitset是一种方法,另一种方法是使用treeset跟踪您分配和撤销的id,这将使id保持有序
例如

public class IdTracker {

    private TreeSet<Long> available;
    private TreeSet<Long> current;

    public IdTracker() {
        this.available = new TreeSet<Long>();
        this.current = new TreeSet<Long>();
    }

    public long getNextId() {
        //Check to see if this is the first time being called, setting initial id to 1
        if (available.isEmpty() && current.isEmpty()) {
            current.add(1L);
            return 1L;
        }

        //Check to see if we have any available values to use
        if (!available.isEmpty()) {
            //Remove from available and assign to current
            Long availableId = available.first();
            available.remove(availableId);
            current.add(availableId);
            return availableId;
        }

        //There are no available id's, get the highest current id and increment
        Long highestCurrentId = current.last();
        Long nextId = highestCurrentId + 1;
        current.add(nextId);
        return nextId;
    }

    public void removeId(long id) {
        //Remove from the current (if there) and place into available
        if (current.remove(id)) {
            available.add(id);
        } else {
            //Handle your failure case
        }
    }
}

所以在你的例子中

private List<Track> tracks;
private IdTracker idTracker;

public void addTrack(Track track) {
    long id = idTracker.getNextId();
    track.setId(id);
    this.tracks.add(track);
}

public void removeTrack(Track track) {
    if (tracks.contains(track)) {
        this.tracks.remove(track);
        this.idTracker.removeId(track.getId());
    } else {
        Terminal.printError("track with id " + track.getId() + " doesn't exist.");
        }
    }
jw5wzhpr

jw5wzhpr2#

一种方法是在另一个数据结构(可能是位集)中跟踪每个分配的id,特别是位集#nextclearbit(int)方法
所以每次你把东西放进 List<Tracks> ,则在位集中设置相对索引,并在 Track 已删除。
像下面这样

BitSet b = new BitSet();
// set the bits while adding tracks
b.set(0);
b.set(1);
b.set(2);

b.clear(1); // some track gets removed, so unset the bit
System.out.println(b); // {0, 2}

System.out.println(b.nextClearBit(0)); // 1

相关问题