user7117118 user7117118 - 21 days ago 5
Java Question

How to call original class method using a object which is masked by Java root class i.e., Object class?

I have List of Lists of type Object which holds the objects of the NormalDistribution and BinomialDistribution classes of org.apache.commons.math3 library. Now i want to call sample() method on those objects but, when i call the method it is throwing a error as sample() is undefined for the Object. How can i make it work without changing the type of List of Lists(because i want to store objects belonging to different class in a single list of lists)?

ArrayList<ArrayList<Object>> distributions = new ArrayList<ArrayList<Object>>();
distributions=[[new NormalDistribution(24,10),new NormalDistribution(100,5)],[new BinomialDistribution(160,0.8)]];
for(int i=0;i<distributions.size();i++){
for(int j=0;j<distributions.get(i).size();j++){
double value = (distributions.get(i).get(j)).sample();//sample() is undefined for the Object
}
}

Answer

Here is the problem:

The NormalDistribution and BinomialDistribution classes don't have a common superclass that has a sample() method. One is a subtype of RealDistribution and the other is a subtype of IntegerDistribution. That means that the respective sample() methods return different types; i.e. double[] and int[] respectively.

So what you need is something like this:

    double sample;
    if (distribution instanceof RealDistribution) {
        sample = ((RealDistribution) distribution).sample()[i];
    } else {
        // The int sample value is converted to a double in the assignment.
        sample = ((IntegerDistribution) distribution).sample()[i];
    }
Comments