user602774
user602774

Reputation: 1103

Sum of elements of any type

public float sum(Object ob) {
    float sum = 0;
    for (int i = 0; i < ob.length; i++) {
        sum += ob[i];
    }

    return sum;
}

How can I implement a function that would return the sum of all the array elements of any type?

Upvotes: 0

Views: 8059

Answers (3)

Stephen C
Stephen C

Reputation: 718708

What you are trying to do is ... basically ... implement a bad design. Arrays of primitives in Java are not type compatible, and you cannot do things on them in a polymorphic fashion.

It is not clear what is the best way to fix your design. But here are a couple of alternatives:

  • Write a overloaded methods for each of the cases that make sense; e.g.

    public int sum(int[] ints) ...
    
    public long sum(long[] longs) ...
    
    public float sum(float[] floats) ...
    

    Then make sure that you call them on primitive arrays whose type is known at compile time.

  • Wrap the arrays in classes, and implement the sum method for each of them:

    public interface NumberArray {
        double sum();
        ...
    }
    
    public class FloatArray {
        private float[] floats;
        public Float(float[] floats) { this.floats = floats; }
        public double sum() {
            double sum = 0.0D;
            for (float f : floats) { sum += f; }
            return sum;
        }
    }
    

    and so on.

It is actually possible to implement a float sum(Object array) method ... like this:

public float sum(Object obj) {
    float sum = 0;
    if (obj instanceof float[]) {
        for (float f : (float[]) obj) {
            sum += f;
        }
    } else if (obj instanceof int[]) {
        for (int i : (int[]) obj) {
            sum += i;
        }
    } else if ...
    } else {
        throw new SomeException("Can't sum one of these ...");
    }
    return sum;
}

but that's non-OO and (IMO) really ugly. Better to fix the design.

Upvotes: 2

Bodman
Bodman

Reputation: 8046

An educated guess, I havnt done java in a while. Is a cast in order?

EDIT: Or, change parameter type to float[]:

float[] ob = (float[]) ob;

public float sum(Object ob) {
    float sum = 0;
    float[] ob = (float[]) ob;
    for (int i = 0; i < ob.length; i++) {
        sum += ob[i];
    }
    return sum;

}

Upvotes: 2

BalusC
BalusC

Reputation: 1108632

As per the comment on the other answer:

java.lang.ClassCastException: [J cannot be cast to [F

Then it's a long[], not a float[]. Just use long, not float or Object. If you declare it explicitly as method argument, then you don't also need to fiddle with casts.

public long sum(long[] array) {
    long sum = 0;
    for (int i = 0; i < array.length; i++) {
        sum += array[i];
    }
    return sum;
}

See also:

Upvotes: 1

Related Questions