Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a ArrayPredicate<A extends Object[]>?

I'm not trying to create an array of a generic type (such as E[]). What I'm trying to do is create a predicate that analyzes a (non-primitive) array, such as

public class ArrayPredicate<A extends Object[]> implements Predicate<A> {    

   public boolean test(A a) {
      if(a == null) return false;
      if(a.length == 0) return false;
      for(Object o: a) {
         if(o == null) return false;
      } 
      return true;
   }    

   ...
}

But Predicate<Object[]> is obviously a compiler error.

UPDATE: I need to extend this to StringArrayPredicate and IntegerArrayPredicate, and so on, in order to validate the specific values of each element. Hence, the class itself must be generified.

How can you create a generified predicate for an array?

like image 857
aliteralmind Avatar asked Feb 10 '26 18:02

aliteralmind


1 Answers

If you want a Predicate<Object[]>, there's no need to make the implementing class itself generic.

This compiles:

public class ArrayPredicate implements Predicate<Object[]> {    

    public boolean test(Object[] a) {
       if(a == null) return false;
       if(a.length == 0) return false;
       for(Object o: a) {
          if(o == null) return false;
       } 
       return true;
    }    
 }

If you do want to parameterize your class:

public class ArrayPredicate<T> implements Predicate<T[]> {
    public boolean test(T[] a) {
        return a != null && a.length > 0 && !Arrays.stream(a).filter(o -> o == null).findAny().isPresent();
    }
}

Note the java-8 refactoring of your method body if you prefer.

like image 50
Bohemian Avatar answered Feb 13 '26 07:02

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!