java - ArrayList 和 Array 作为构造函数的参数

标签 java arrays arraylist parameters constructor

我正在为计算机科学课做作业,但我陷入了这一部分。我应该为给定的主方法和实例变量编写构造函数。构造函数需要有一个 ArrayList 和一个 Array 作为参数,但我不完全确定如何做。

使用说明及主要方法如下:

Use the comments and the code provided to complete the constructor

import java.util.ArrayList;
class RectangleStats
 { 
 //instance variables go here

 //The constructor for the RectangleStats class takes an ArrayList and an array as parameters for

 // width and length, respectively.


 // code for constructor goes here
 // The RectangleStatsTesterClass assigns the width of two rectangles to an ArrayList and assigns the
 // length of two rectangles to an array. The calcRectangleArea() and printArea() methods are invoked to 
 // calculate and print the area of the two rectangles.
 public class RectangleStatsTesterClass 
 { 
       public static void main(String[] args)

 {

       ArrayList dblWidth = new ArrayList();

       dblWidth.add(5.2);

       dblWidth.add(9.3);

       double [ ] dblLength = {11.1, 4.7};


       RectangleStats rectStats = new RectangleStats(dblWidth, dblLength);


       rectStats.calcRectangleArea();

       rectStats.printArea();

       }

  }

我目前拥有的构造函数是这样的: 公共(public)矩形统计(双 w,双 l) { 宽度=w; 长度=l; 面积=0; }

但我不确定它是否正确..帮助?

最佳答案

如果你传递的实际参数是ArrayListarray分别,那么你的方法签名中的形式参数也应该是相同的。即:

public RectangleStats(ArrayList<Double> arg0, double[] arg1)

然后您将分配 arg0arg1 (或者无论你的标识符是什么)到你的实例变量。

话虽如此,实现背后的整个想法非常糟糕(例如:使用 ArrayListarray 而不是其中之一)。

此外,当您声明 ArrayList 时,按如下方式执行此操作: ArrayList<Double> dblWidth = new ArrayList<Double>();

指定要添加的对象的类几乎总是更好。

关于java - ArrayList 和 Array 作为构造函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124816/

相关文章:

java - 传递字符串对象时使用 apache poi 格式化日期

php - 两个 while 循环到单个数组?

c - 警告:从不兼容的指针类型传递''的参数1 [默认启用]

ArrayList 上的 java.util.ConcurrentModificationException

java - XML属性互值对的排序算法

java - BufferSize 在 log4j xml 配置中的位置

java - 如何在 Java 代码中使用 scala.None

javascript - 如何将键值元组数组转换为对象

java - 由 JButton 组成的 ArrayList。但没有按预期工作

java - 当父级为抽象时,将 ArrayList<Parent> 的类型更改为 ArrayList<Child>