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;
“… 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)
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 anObject[]
) – Raw Types should not be used anymore, accepted just so legacy code still runs. Use something likeArrayList<Country> thisList
(assuming the list contains instances ofCountry
, otherwise use the correct class name)This code wouldn’t compile, the error it causes should be pretty informative. If you have an
ArrayList
ofCountry
objects, then you should specify that you accept aList<Country>
for yourthisList
parameter.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. Anddiff*diff
is shorter and avoids a method call.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 genericsArrayList<Country>
. UsingList<Country>
will give you flexibility about the type ofList
you use at instantiationMaybe you should edit the question to show before and after versions of your code.