I was asked to demonstrate a Singleton class design for my assignment. The version I submitted uses Strings and works fine, but I just can't get the reserveLane method to work properly with integers. Whenever I call the reserveLane method in the code below, it removes the element with the index of the integer passed into it instead of the element containing the value that matches the integer passed in. The program is supposed to print each message in the removeLane method once.
import java.util.*;
public class Race {
// store one instance
private static final Race INSTANCE = new Race(); // (this is the singleton)
List<Integer> lanes = new ArrayList<>();
public static Race getInstance() { // callers can get to
return INSTANCE; // the instance
}
private Race() {
lanes.add(1);
lanes.add(2);
}
public void removeLane(int lane) {
if(lanes.contains(lane)){
lanes.remove(lane);
System.out.println("Lane successfully reserved.");
} else {
System.out.println("Lane is already reserved.");
}
}
public static void main(String[] args) {
assignLane(1);
assignLane(1);
}
private static void assignLane(int lane) {
Race race = Race.getInstance();
race.removeLane(lane);
}
}
I'm wondering if I'm wasting my time trying to go this route or is there a way to fix it?
lanes.remove(new Integer(lane));instead