commons-issues mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Piotr Wydrych (JIRA)" <j...@apache.org>
Subject [jira] [Commented] (MATH-942) DiscreteDistribution.sample(int) may throw an exception if first element of singletons of sub-class type
Date Sat, 09 Mar 2013 22:19:13 GMT

    [ https://issues.apache.org/jira/browse/MATH-942?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=13598071#comment-13598071
] 

Piotr Wydrych commented on MATH-942:
------------------------------------

bq. I am a bit reluctant to use Object[] as your patch, though. Are you sure it would always
work? I know type erasure occurs, but with your patch, we mainly apply it ourselves. Is it
safe?

I did some reading, scanning other generics classes code, and testing. It seems that there
are two proper ways to do it:
# return {{Object[]}}, or
# return {{List<T>}}.

I suggest returning {{Object[]}}, like {{ArrayList.toArray()}}. I've attached an updated patch.

Then, the following code will work:

{code}
public class X {

    public static void main(String[] args) {
        List<Pair<X, Double>> list = new ArrayList<Pair<X, Double>>();
        list.add(new Pair<X, Double>(new X(), new Double(1)));
        X[] xarr;
        Object[] oarr;
        try {
            xarr = (X[]) new DiscreteDistribution<X>(list).sample(1);
            throw new RuntimeException("Expected ClassCastException");
        } catch (ClassCastException e) {
        }
        oarr = new DiscreteDistribution<X>(list).sample(1);
    }
}
{code}
                
> DiscreteDistribution.sample(int) may throw an exception if first element of singletons
of sub-class type
> --------------------------------------------------------------------------------------------------------
>
>                 Key: MATH-942
>                 URL: https://issues.apache.org/jira/browse/MATH-942
>             Project: Commons Math
>          Issue Type: Bug
>            Reporter: Piotr Wydrych
>         Attachments: DiscreteDistribution.java.patch
>
>
> Creating an array with {{Array.newInstance(singletons.get(0).getClass(), sampleSize)}}
in DiscreteDistribution.sample(int) is risky. An exception will be thrown if:
> * {{singleons.get(0)}} is of type T1, an sub-class of T, and
> * {{DiscreteDistribution.sample()}} returns an object which is of type T, but not of
type T1.
> To reproduce:
> {code}
> List<Pair<Object,Double>> list = new ArrayList<Pair<Object, Double>>();
> list.add(new Pair<Object, Double>(new Object() {}, new Double(0)));
> list.add(new Pair<Object, Double>(new Object() {}, new Double(1)));
> new DiscreteDistribution<Object>(list).sample(1);
> {code}
> Attaching a patch.

--
This message is automatically generated by JIRA.
If you think it was sent incorrectly, please contact your JIRA administrators
For more information on JIRA, see: http://www.atlassian.com/software/jira

Mime
View raw message