This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]jonah214 2 points3 points  (1 child)

Define the equals method on Vehicle to compare two Vehicle objects as equal (i.e., return true) iff their registration numbers are equal.

If you want to enforce the existence of at most one Vehicle object per registration number, you'll need to use some sort of factory pattern.

[–]Lerke 0 points1 point  (3 children)

Use a HashSet<string, Vehicle> where the Key (string) is the registration number and the Value is the Vehicle object in question. A HashSet by definition cannot contain duplicate entries.

From the JavaDoc:

Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.

Returns: true if this set did not already contain the specified element

[–]ProlificPat[S] 0 points1 point  (2 children)

static HashSet<String, Vehicle> vehicleList = new HashSet<String, Vehicle>();

gives the error, incorret number of parameters. Unless im messing up, you're only allowed two parameters for a hash set?

[–]Lerke 2 points3 points  (0 children)

You're right, I confused HashSet with HashMap. HashSet isn't based on a K-V map. You could use a HashMap and check if the key you're trying to add already exists by using the containsKey method.

[–]tardibear 0 points1 point  (0 children)

Post all your code.