java - 我需要将 ArrayList 转换为数组

标签 java arrays arraylist

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;

public class CylinderList2 {
    private String listName = "";
    private ArrayList<Cylinder> cyll =
            new ArrayList<Cylinder>();

    /**
     * @param cyllIn     Represents list of cylinder objects.
     * @param listNameIn Represents name of list.
     */
    public CylinderList2(String listNameIn,
                         ArrayList<Cylinder> cyllIn) {
        listName = listNameIn;
        cyll = cyllIn;
    }

    /**
     * @return A String representing the name of the list. Returns a string that represents name of
     * the list.
     */
    public String getName() {
        return listName;
    }

    /**
     * @return The number of Cylinder objects. Returns the number of cylinder objects.
     */
    public int numberOfCylinders() {
        return cyll.size();
    }

    /**
     * @return Total area. Returns total area of cylinder objects.
     */
    public double totalArea() {
        double tArea = 0;
        int index = 0;

        if (cyll.size() == 0) {
            return 0;
        }

        while (index < cyll.size()) {
            tArea += cyll.get(index).area();

            index++;
        }
        return tArea;
    }

    /**
     * @return Displays volume when method is called. Returns total volume of cylinder objects.
     */
    public double totalVolume() {
        double tVolume = 0;
        int index = 0;

        if (cyll.size() == 0) {
            return 0;
        }

        while (index < cyll.size()) {
            tVolume += cyll.get(index).volume();

            index++;
        }
        return tVolume;
    }

    /**
     * @return Displays height when method is called. Returns double representing total height of
     * all cylinder objects.
     */
    public double totalHeight()

    {

        double tHeight = 0;

        int index = 0;

        if (cyll.size() == 0)

        {

            return 0;

        }

        while (index < cyll.size())

        {

            tHeight += cyll.get(index).getHeight();


            index++;

        }

        return tHeight;

    }
}

我需要将 ArrayList 转换为数组,但我不太喜欢如何做到这一点。我是初学者,所以我仍在学习如何正确使用数组。我对这两者感到困惑,因为他们与我相似,而且我不知道如何与他们合作。任何帮助将不胜感激

最佳答案

Cylinder[] array = new Cylinder[cyll.size()];
cyll.toArray(array);

关于java - 我需要将 ArrayList 转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33264384/

相关文章:

java - 使用 StringBuilder 将字符串的 ArrayList 连接成单个字符串

尝试显示数组时发生 Java 异常

java - ClassCastException : java. lang.Object[] 无法转换为 java.lang.String[] android

java - 自动售货机,输入变量无法识别以进行计算

java - 有没有比 "pet store"更好的方法来比较 .Net 和 Java 在电子商务设置中的一般性能?

java - 用于创建 JasperReport 后未释放池连接

java - 套接字数组

php - 如何使用 codeigniter 框架从主键数组中获取查询

javascript - 我可以安全地传递给 function.apply()/spread 运算符的最大数组

javascript - 如何将项目分配给选择器以获取数据列表作为数组形式的响应?