I need circular list of objects. And each one should know which is previous or next. I did this:
class Bus {
private Bus previous;
private Bus next;
public Bus() {
//anything
}
public void setPrevious(Bus bus) {
this.previous = bus;
}
public void setNext(Bus bus) {
this.next = bus;
}
private void someMethod() {
// if (previous.xxx() && next.xxx()) {
// do something
// }
}
}
And I created an array of Bus. After I add all buses into it, I set next and previous of each element. And I feel it’s ugly:D. May you suggest me better way?
If you adjust your
setNextandsetPreviousmethods to not only update their instance but also the instance that is set asnextand aspreviousyou want have to depend on an external mechanism.So let’s say you have initially created
BusAandB. When you callA.setNext( B ), it should also update the previous node ofB, without having to callB.setPrevious( A ). Similar as when you add something to aLinkedListin Java, you do not have to manually set the link between the last object and the object you just added. Something likeOf course then you still have to consider the scenario where the bus is already contained in another
Listthat you have to update thatListas well.Therefore, the suggestion to separate the nodes from the actual bus instances as suggested in one of the other responses is a better idea. This allows you to add busses to multiple lists, and makes it probably easier to write your circular list (or just use an available implementation for the list). This is also better OO design as you can reuse the list you wrote.