Java中优化类的思路

Java中优化类的思路,java,oop,optimization,constructor,Java,Oop,Optimization,Constructor,这是我编写的一个类,感觉很“笨重”,好像应该有更好的方法来设置它,而不需要额外的方法setList()来实例化数组。我试图只留下与我的问题相关的部分,以及我第一次抛出运行时(而非编译时)错误的示例。我仍然习惯于解释性语言,因此Java的更严格规则需要一些时间来适应 public class Numbersplode { // fields private int before; private int goal; private int[] processed;

这是我编写的一个类,感觉很“笨重”,好像应该有更好的方法来设置它,而不需要额外的方法
setList()
来实例化数组。我试图只留下与我的问题相关的部分,以及我第一次抛出运行时(而非编译时)错误的示例。我仍然习惯于解释性语言,因此Java的更严格规则需要一些时间来适应

public class Numbersplode
{
   // fields
   private int before;
   private int goal;
   private int[] processed;

   // constructors
   Numbersplode(int begin, int finish)
   {
      this.before = begin;
      this.goal = finish;
      this.processed = this.setList(begin);
      this.transList();
   }

   // mutators
   private int[] setList(int begin)
   {
      int[] result = new int[begin];
      return result;
   }

   public void transList()
   {
      // transforms the list
      int count;
      double temp;

      for (count = 0; count < this.before; count++)
      {
         temp = (double)count/(double)this.before * (double)this.goal;
         this.processed[count] = (int)temp;
      }
   }
}
我收到
java.lang.ArrayIndexOutOfBoundsException:0
,因为
处理[]
显然不能以这种方式定义

这个额外的类似乎解决了这个问题,但在我看来,构造函数应该在创建对象的同时定义这些变量,从而允许以这种方式同时定义数组
处理的

那么,我还缺少一个更优雅的解决方案吗?如果我在问题解决之前找到一个,我会把它贴在这里

编辑


需要明确的是,如果我编译类(甚至是一个从该类创建对象的程序),在我实际运行程序之前,我不会有任何问题(因此,运行时问题与compiletime,但希望明确)

为什么还要有一个
setList()
方法--私有的(?)变异器。为什么不在构造函数中简单地设置
processed=newint[before]

Numbersplode(int before, int goal) {
  this.before = before;
  this.goal = goal;
  processed = new int[before];
  transList();
}

获得越界异常的原因是在构造函数中设置
之前实例化数组。在Java中,操作顺序是初始化部分发生在构造函数体之前。只需在前面设置
之后实例化数组,就像@HovercraftFullOfEels建议的那样。编辑代码,以便我现在可以阅读我错过的部分@事实上,它藏起来了。因此,超出范围0而不是空指针。但这并不会真正改变你的答案。@ElliottFrisch-我明白你的意思(我想),但这不是我稍后在编写这个类的访问器/目的中所做的。不过我可能遗漏了一些东西。@ElliottFrisch没有,为了使用它,我需要生成的数组与初始数组相同(当类实例化时,
begin
捕获的数组)。这可能看起来很奇怪,但这是因为我需要:)
Numbersplode(int before, int goal) {
  this.before = before;
  this.goal = goal;
  processed = new int[before];
  transList();
}