1

I have a ArrayList that's not specified as double/float but it contains double float values as 22.33, 12.56, 34, 21...

I actually have two that I use when I read from a file to savee the data to. They look like this

static List<MySample> data = new ArrayList<MySample>();
static ArrayList list = new ArrayList();

With ArrayList<Double> list = new ArrayList(); I can use a simple loop like:

double sum = 0;
double count = 0;
for (Double a : list) {
    sum += a; 
    count++;
}
System.out.println("Average is   " + sum / count);

But when I use:

for (Object o : list) {
    // How can I do the same with some code here?
}

How can I do the same with the Object loop? I hope you did understand my problem.

Ok, here is my method where I unserialize a file and where I want to get the values from...

public void deserialize(List<MySample>listan, String path) {
   double sum=0;
   int count=0;
try {File file = new File(path);ObjectInputStream in = new 
   ObjectInputStream(newFileInputStream(file));             
   listan = (ArrayList<MySample>) in.readObject();


        for(Object obj: listan){

            //here I need the code
}
         System.out.println("Good work!");
        in.close();
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (ClassNotFoundException ex) {
        System.out.println(ex.getMessage());
    }

}
Tapani Yrjölä
  • 168
  • 1
  • 4
  • 15
  • 4
    Either enforce the List to accept or cast it. – gtgaxiola May 18 '15 at 13:16
  • 5
    Why `list` is a raw-type? – Maroun May 18 '15 at 13:17
  • Preferred way is to be specific about the list type as `Double` or `Float` – TSKSwamy May 18 '15 at 13:18
  • 3
    You should always use _generic_ collections. See this answer for a quick intro: http://stackoverflow.com/questions/14207005/why-warning-arraylist-is-a-raw-type-references-to-generic-type-arrayliste-sh/14207100#14207100 – Natix May 18 '15 at 13:18
  • 1
    You should, at the very least, use: `static List list` since `Double` and `Float` extend `Number`. – Mr. Polywhirl May 18 '15 at 13:19
  • One more reason to [use a generic type](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). TL;DR: the only reason it is possible to use raw types is backwards compatibility. – Turing85 May 18 '15 at 13:23

6 Answers6

2

If you ensure list contains all double values, cast it to Double (in order not to break the whole loop, have to put try/catch in the loop... It maybe not high performance):

for (Object o : list) {
    try {
        sum += ((Double)o).doubleValue();
        count++;
    } catch(ClassCastException e) {
    }
}

But suggest not to use raw type list like ArrayList list = new ArrayList();, the better way is List<Double> list = new ArrayList<Double>();.

coderz
  • 4,847
  • 11
  • 47
  • 70
  • And what to add/do if it is not a Double? ;) – dbf May 18 '15 at 17:10
  • @dbf If the `list` cannot ensure all elements are double, I have to add `try/catch` within the loop, because if one element cannot be cast to double, it should not break the whole loop. Only when no exception happens the count should increase one. – coderz May 19 '15 at 06:14
1

While the following will work for you:

        Double sum = (double) 0;
        int count =0;
        for (Object o: list){
            sum= sum+ (Double)o;
            count++;
        }
        System.out.println("Average is   " + sum / count);

What you should do is use Generics which provide compile-time type safety.

        ArrayList<Double> list = new ArrayList<Double>();
        list.add(22.33);
        list.add(12.56);
        list.add(34.21);

        Double sum = (double) 0;
        int count =0;
        for (Double o: list){
            sum= sum+ o;
            count++;
        }
        System.out.println("Average is   " + sum / count);
Kedar Parikh
  • 1,241
  • 11
  • 18
0

You can cast:

for (Object o:list){
    sum += (double) o;
    count++;
}
chris
  • 161
  • 5
0

You can just cast the object a Double, at least if you're sure the objects are of type Double. It's basically the old way of doing things, from before Java 5.

for (Object o:list){
     total += ((Double)o).doubleValue();
}
Steven De Groote
  • 2,187
  • 5
  • 32
  • 52
0

You should, at the very least, use: static List<Number> list since Double and Float extend Number.

Then for your sum, you can get the double value. This is the proper use of generics.

import java.util.ArrayList;
import java.util.List;

public class NumberList {
    public static void main(String[] args) {
        List<Number> list = new ArrayList<Number>();

        list.add(1.4142135623730950);
        list.add(2.71828f);
        list.add(3.14159265359d);

        // Average is: 2.4246954309812287
        System.out.println("Average is: " + avg(list));
    }

    public static double avg(List<Number> list) {
        double sum = 0;
        double count = 0;

        for (Number a : list) {
            sum += a.doubleValue();
            count++;
        }

        return sum / count;
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Also, you do not need to keep track of a count, unless you are skipping values in the list. Simply use `list.size()` as the denominator in the return statement. – Mr. Polywhirl May 18 '15 at 13:43
0

I tried all of the above but it did not work, but I figured it out.

My method looks like this

public void deserialize(List <MySample>listan, String path) {
   double sum=0;
   int count=0;
   double average=0;
    try {
        File file = new File(path);
        ObjectInputStream in = new ObjectInputStream(new   
        FileInputStream(file));
        listan = (ArrayList<MySample>) in.readObject();

        for (Object o:listan){

            sum += Double.parseDouble((String) o);
            count ++;
            average = sum/count;

}

         System.out.printf("The average on %s är %.2f ", item, average);

        in.close();
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (ClassNotFoundException ex) {
        System.out.println(ex.getMessage());
    }

}

It struck me that Java has many types of code that does the same thing. Why just not have one general line of code for this? There is example differents codes that does the same thing but did not work with my methods...example

sum += a.doubleValue();
sum += (double) o;
sum += ((Double)o).doubleValue();

Theese did not work but this code did the work for me

 sum += Double.parseDouble((String) o);
Tapani Yrjölä
  • 168
  • 1
  • 4
  • 15