java stream return array of parameterized class -


situation:

public class p {      public static  predicate<double> isequal(double value) {         return p -> (math.abs(p - value) <= 0.000001);     } }  public class entity {        private double[] values;      public double getvalue(int index) {         return values[index];     } } 

code unchecked conversion:

public attribute split(entity[] examples) {     @suppresswarnings("unchecked")      predicate<double>[] pa = arrays.stream(examples).map(e -> p.isequal(e.getvalue(a.index))).toarray(predicate[]::new);     return ...; } 

how can solve without unchecked conversion?

i can't use such:

public attribute split(entity[] examples) {     predicate<double>[] pa = arrays.stream(examples).map(e -> p.isequal(e.getvalue(a.index))).toarray(predicate<double>[]::new);     return ...; } 

there no way create generic array without unchecked conversion, creation of generic array unsafe operation per se. since creation not allowed, can create non-generic array , perform unchecked conversion.

simply said, every operation enable subsequent heap pollution without warning, must considered unsafe operation either, generates warning or produce error. problem can demonstrated:

predicate<double>[] p=/* someway array*/; object[] array=p; array[0]=(predicate<integer>)i -> i==0; 

this situation, array elements declared of type predicate<double>, 1 of them predicate<integer>, called heap pollution. since both, assignment of p variable of type object[] , assignment of predicate<integer> element of array of type object[], legal constructs don’t generate warnings, creation of array must considered unsafe operation must generate either, warning or error, prevent subsequent silent heap pollution. otherwise, generics not claim provide compile-time safety, i.e. code free of unchecked/unsafe operations guarantees absence of heap pollution.

the exception generic array creation accepted, in context of varargs, have warning free code, i.e. using @safevarargs, have accept fundamental restrictions, e.g. can not assign array other variable nor return method, avoid sneaky introduction of problem described above.

so bottom line is, either, accept there unchecked operation or use list , “use list” means use list, not try create array via list. fundamental difference between list , array can’t assign list<predicate<double>> list<predicate> nor list<object> (without unchecked operation), provides safety generics promise.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo