Home > Net >  What edits should I make to my constructor?
What edits should I make to my constructor?

Time:10-27

I am trying to implement some functions to a generic array such as setting the count of the item to int count via method setcount( DT item, int count). I've asked this before and a kind Stack Overflow user has been nice enough to explain that using a hashmap would've been better.

class SimpleHistogram<T> implements Histogram<T>, Iterable<T> {

    private final Map<T, Integer> bins = new HashMap<>();

    public SimpleHistogram() {
        this(List.of());
    }

    SimpleHistogram(List<? extends T> items) {
        for (T item : items) {
            Integer count = bins.getOrDefault(item, 0);
            bins.put(item, count   1);
        }
    }

    @Override
    public void setCount(T item, int count) {
        bins.put(item, count);
    }

    @Override
    public Iterator<T> iterator() {
        return bins.keySet().iterator();
    }

}
    @Override
    public int getTotalCount() {
        return bins.size();
    }

However, there seems to be an error when I tried to run it using my test cases and it seems that the issue stems from the constructor that I'm provided with.

I've tried to debug the issue but the only solution available is to change from

public SimpleHistogram() {
        this(List.of());
    }

to

public SimpleHistogram(Character[] target) {
            this(List.of());
        }

which would be wrong since it should take in any generic array.

Any suggestions on what changes should I make?

Here are the test cases by the way: public class SimpleHistogramTest {

@Test
public void testHistogram() {
    Character[] target = {'a','b','c','a'};
    Histogram<Character> h = new SimpleHistogram<>(target); //here is where the problem arises
    Iterator<Character> iter = h.iterator();
    int elemCount = 0;
    while(iter.hasNext()) {
        iter.next();
        elemCount  ;
    }

    assertEquals(3, elemCount);
    assertEquals(2, h.getCount('a'));
    assertEquals(1, h.getCount('b'));
    assertEquals(1, h.getCount('c'));
    assertEquals(4, h.getTotalCount());

CodePudding user response:

You should overload your constructor with a new one which is handle the arrays or have to pass the array as list.

  SimpleHistogram(T[] items) {
    this(Arrays.asList(items));
}

or

 @Test
public void testHistogram() {
    Character[] target = {'a','b','c','a'};
    Histogram<Character> h = new SimpleHistogram<>(Arrays.asList(target)); 
    Iterator<Character> iter = h.iterator();
    int elemCount = 0;
    while(iter.hasNext()) {
        iter.next();
        elemCount  ;
    }
}

Or you can use the 3 dot syntax for parameters.

SimpleHistogram(T... items) {
    this(Arrays.asList(items));
}
  • Related