The method size() is undefined for the type test<double>

2.1k Views Asked by At

Hello Im Getting an error on this line "int N = numbers.size();" says The method size() is undefined for the type Test<Double. Any assistance would be appreciated.

Way to code method size?

So from my understanding is not getting what the size is? Because the values will be getting inputted through console does it need a size?


    
    public class Test<Item> implements Iterable<Item>
    {
    private Node first; // first node in list
    private class Node
    {
    Item item;
    Node next;
    }
    public void add(Item item)
    { // same as push() in Stack
    Node oldfirst = first;
    first = new Node();
    first.item = item;
    first.next = oldfirst;
    }
    
    public Iterator<Item> iterator()
    { return new ListIterator(); }
    private class ListIterator implements Iterator<Item>
    {
    private Node current = first;
    public boolean hasNext()
    { return current != null; }
    public void remove() { }
    public Item next()
    {
    Item item = current.item;
    current = current.next;
    return item;
    }
    }
    
    
    
    
3

There are 3 best solutions below

0
Mureinik On

Your test class doesn't implement a size() method, so you can't call it, as you've seen. Looking at how you use it, you don't need it either - if you're iterating over it, you can count the iterations as you go to deduce the size:

double sum = 0.0;
int size = 0;
for (double x : numbers) {
    sum += x;
    ++size;
}
double mean = sum / size;
0
Prophet On

As you defined, your class Test<Item> implements Iterable<Item>.
While Iterable<Item> interface does not have .size() method definition.
Your class Test<Item> does not implement .size() method implementation.
This is why numbers who is an instance of Test<Item> does not have .size() method defined.

0
user16632363 On

From the code you deleted, which is code that is needed to answer your question:

int N = numbers.size();
double sum = 0.0;
for (double x : numbers)

The compiler complains that you have not defined 'size' but you yourself coded a call to 'size'. Only you can say whether you actually need it; you're the programmer.