Reputation: 11
i am using hashmap to validate that key dosent exist in the map and adding the key to a list i am using containsKey to prevent duplicate but its adding duplicate to my list
private static void makeList(int n,ArrayList<Integer> minimum ,HashMap<Integer,Integer> ugly) {
for(int i=1; minimum.size() < n; ++i) {
if(!ugly.containsKey(2*i)); {
minimum.add(2*i);
ugly.put(2*i,2*i );
}
int m3=3*i;
if(!ugly.containsKey(3*i)){
minimum.add(3*i);
ugly.put(3*i,3*i);
}
int m5=5*i;
if(!ugly.containsKey(m5)){
minimum.add(m5);
ugly.put(m5,m5);
}
}
}
Upvotes: 0
Views: 87
Reputation: 18245
Be simple and it clear the code.
private static void makeList(int n, List<Integer> minimum, Map<Integer,Integer> ugly) {
for (int i = 1; minimum.size() < n; i++)
for (int j : Arrays.asList(2, 3, 5))
if(ugly.put(i * j, i * j) == null)
minimum.add(i * j);
}
P.S. Why don't you use Set<Integer>
instead of Map<Integer, Integer>
with key == value
?
Upvotes: 0
Reputation: 536
I see you gave semicolon ;
after if()
condition
just remove that and try
private static void makeList(int n,ArrayList<Integer> minimum ,HashMap<Integer,Integer> ugly) {
for(int i=1; minimum.size() < n; ++i) {
if(!ugly.containsKey(2*i)) { //<-edited part, removed semicolon
minimum.add(2*i);
ugly.put(2*i,2*i );
}
int m3=3*i;
if(!ugly.containsKey(3*i)){
minimum.add(3*i);
ugly.put(3*i,3*i);
}
int m5=5*i;
if(!ugly.containsKey(m5)){
minimum.add(m5);
ugly.put(m5,m5);
}
}
Upvotes: 2