Trying to recreate a program using an arrayList instead of an array

I created this program the first time using an array but now I have to use an ArrayList for it. Im having trouble converting one of my methods to use the arrayList instead of an array.

This is the code I have
My main problem is that I cant call my getcPerCases because it is in a different class called Country and it wont call it.

public static double standardDev(ArrayList thisList, int thisLim, double thisAvg)
{
    double diff; 
    double totalDiff = 0;
    double standardDev;
    int x;
    thisLim = thisList.size();
    for(x = 1; x <= thisLim; x++)
    {
        diff = (thisList.get(x-1).getcPerCases() - thisAvg); Math.pow(diff,2);
        totalDiff += diff;
    }
    
    standardDev = Math.sqrt(totalDiff/thisLim);
    return standardDev;

  • 1

    quick scan shows ArrayList thisList – this is declaring a Raw Type ArrayList, that is, one without any type information (that would be kind of equivalent to an Object[]) – Raw Types should not be used anymore, accepted just so legacy code still runs. Use something like ArrayList<Country> thisList (assuming the list contains instances of Country, otherwise use the correct class name)

    – 




  • 1

    This code wouldn’t compile, the error it causes should be pretty informative. If you have an ArrayList of Country objects, then you should specify that you accept a List<Country> for your thisList parameter.

    – 

  • 2

    You have a lone statement Math.pow(diff,2); at the end of an expression. And the result is not being assigned to anything. I am presuming the preceding ; might be a mistake. And diff*diff is shorter and avoids a method call.

    – 




  • 1

    In the ‘old days’, that should have been diff = (((Country)thisList.get(x-1)).getcPerCases() - thisAvg); and it will work now, but as others have said, you should use strong typing with the generics ArrayList<Country>. Using List<Country> will give you flexibility about the type of List you use at instantiation

    – 




  • 1

    Maybe you should edit the question to show before and after versions of your code.

    – 

“… This is the code I have My main problem is that I cant call my getcPerCases because it is in a different class called Country and it wont call it. …”

Specify the data-type, for the ArrayList.

public static double standardDev(ArrayList<Country> thisList, int thisLim, double thisAvg)

Here is the Java tutorial on Generics.
Lesson: Generics (Updated) (The Java™ Tutorials > Learning the Java Language)

Leave a Comment