简体   繁体   中英

Writing a constructor of a class that extends an ArrayList

This is the signature of my class:

public class Constraint extends ArrayList<Interval> {
    // ...
}

the other class Interval:

public class Interval {
    // ...
}

has two int s, first and last

Constructor:

public Interval(int first, int last) { 
    this.first = first;
    this.last = last;
}

A method that returns the union of two Intervals or more but should be of Constraint type:

 public Constraint union(Interval interval) {
     Interval a = new Interval(first, end);
     int l = 0;
     int max = 0;
     // Interval result = new Interval(l, max);
     l = (a.first < interval.end) ? a.first : interval.end;
     max = (a.end > interval.end) ? a.end : interval.end;
     return new Interval(l, max); 
     // the return here will return a new interval of type Interval but
     // the method that I'm suppose to write should return something of
     // type Constraint
}

My main issue is: how can I write the following constructor?

 public Constraint(Collection<Interval> collection) throws  NullPointerException {
    // if the collection is empty, I have to write something like this: 
    if (collection == null) {
        throw new NullPointerException("collection is empty");
    }
    // ...
}

Any help on how I should write the constructor of the class Constraint is really appreciated.

You have stumbled upon a deficiency of Java: the call to super() must be the first call in your constructor, so you are not allowed to precede it with code that checks against null. There is no good reason for this limitation, it is just the way java is. A flaw in the language. (If you learn Scala you will see that it totally did not have to be this way.)

So, the solution is to do the null-check in the same statement as the call to super . The following should accomplish this:

public Constraint( Collection<Interval> collection ) 
{
    super( Objects.requireNonNull( collection ) );
}

If your version of java does not have Objects.requireNonNull() you can code a private static function yourself which checks the collection for nullity, throws if null , or returns the collection as-is if not null .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM