Java 编写扩展ArrayList的类的构造函数
这是我班的签名:Java 编写扩展ArrayList的类的构造函数,java,constructor,Java,Constructor,这是我班的签名: 公共类约束扩展了ArrayList{ // ... } 另一节课间隔: public class Interval { // ... } 有两个ints、first和last 建造商: public Interval(int first, int last) { this.first = first; this.last = last; } 返回两个或多个间隔的并集但应为约束类型的方法: public Constraint union(Inte
公共类约束扩展了ArrayList{
// ...
}
另一节课间隔:
public class Interval {
// ...
}
有两个int
s、first
和last
建造商:
public Interval(int first, int last) {
this.first = first;
this.last = last;
}
返回两个或多个间隔的并集但应为约束类型的方法:
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
}
公共约束联合(间隔){
间隔a=新间隔(第一个,结束);
int l=0;
int max=0;
//间隔结果=新间隔(l,最大值);
l=(a.firstinterval.end)?a.end:interval.end;
返回新间隔(l,最大值);
//此处的返回将返回一个新的interval类型,但
//我想写的方法应该返回
//类型约束
}
我的主要问题是:如何编写以下构造函数
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");
}
// ...
}
公共约束(集合)引发NullPointerException{
//如果集合为空,我必须这样写:
if(集合==null){
抛出新的NullPointerException(“集合为空”);
}
// ...
}
非常感谢您对我应该如何编写类约束构造函数的任何帮助 您偶然发现了Java的一个缺陷:对
super()
的调用必须是构造函数中的第一个调用,因此不允许在调用之前使用检查null的代码。这种限制没有充分的理由,它只是java的方式。语言上的缺陷。(如果你学习Scala,你会发现它完全不必是这样。)
因此,解决方案是在调用super
的语句中执行空检查。应通过以下措施实现这一点:
public Constraint( Collection<Interval> collection )
{
super( Objects.requireNonNull( collection ) );
}
公共约束(集合)
{
super(Objects.requirennull(collection));
}
如果您的java版本没有
对象。requireNonNull()
您可以自己编写一个私有静态函数,该函数检查集合是否为空,抛出Ifnull
,或者返回集合,如果不是null
,您好,我已经修复了您的格式设置。下次请你自己处理。这个问题似乎有很多不相关的代码。当您在使用约束构造函数时,该union
方法用于什么?请阅读,然后相应地回答你的问题。特别是,构造函数有什么问题吗?