java - 如何使用构造函数进行java静态数组初始化?

标签 java arrays oop static

我有以下类,下面列出了数组的静态字段。 您能否告诉/解释我如何创建构造函数来初始化所有数组并将其传递给 public static void BookInfo 方法。非常感谢任何帮助!

  public class BookInfo {

    // Global arrays accessible by all methods
public static String[] isbnInfo = {

        "978-0060014018",
        "978-0449221431",
        "978-0545132060",
        "978-0312474881",
        "978-0547745527"

      };


public static String[] bookTitleInfo = {

            "The Greatest Stories",
            "The Novel",
            "Smile",
            "The Bedford Introduction to Drama",
            "AWOL on the Appalachian Trail"

           };

public static String[] authorInfo = {

         "Rick Beyer",
         "James A. Michener",
         "Raina Telgemeier",
         "Lee A. Jacobus",
         "David Miller"

        };

public static String[] publisherInfo = {

            "HerperResource",
            "Fawcett",
            "Graphix",
            "Bedford St. Martins",
            "Mariner Books"

            };

public static String[] dateAddedInfo = {

            "05/18/2003", 
            "07/07/1992", 
            "02/01/2010", 
            "09/05/2008", 
            "11/01/2011"

            };

public static int[] qtyOnHandInfo = {7, 5, 10, 2, 8};

public static double[] wholesaleInfo = {12.91, 7.99, 6.09, 54.99, 10.17};

public static double[] retailInfo = {18.99, 3.84, 4.90, 88.30, 14.95};

public static void BookInfo() {

    System.out.println("             Serendipity Booksellers");
    System.out.println("                Book Information\n");       


    for(int i = 0; i < isbnInfo.length; i++){

        System.out.println("ISBN: " + isbnInfo[i]);
        System.out.println("Title: " + bookTitleInfo[i]);
        System.out.println("Author: " + authorInfo[i]);
        System.out.println("Publisher: " + publisherInfo[i]);
        System.out.println("Date Added: " + dateAddedInfo[i]);
        System.out.println("Quantity-On-Hand: " + qtyOnHandInfo[i]);
        System.out.println("Wholesale Cost: $ " + wholesaleInfo[i]);
        System.out.println("Retail Price: $ " + retailInfo[i]);
        System.out.println();

         }
            }
    }

最佳答案

你想要做的是使用一个static block 。 static 数据在运行任何其他代码之前 被初始化。 constructor 仅在对象实例化时调用,每次 实例化该类型的对象时都会调用它们,static 初始化一次当应用程序运行时。

public static final String[] ISBN_INFO; 

static 
{ 

    BookInfo.ISBN_INFO = {
    "978-0060014018",
    "978-0449221431",
    "978-0545132060",
    "978-0312474881",
    "978-0547745527" }; 

  // do the same thing with the other blocks

}

static 变量也设为final 也是一个好主意。

关于java - 如何使用构造函数进行java静态数组初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12956954/

相关文章:

java - Spring 重试 XML 等效于 @EnableRetry

JavaScript 创建对象数组

javascript - Typescript 和 Javascript ES6、ES.NEXT 类构造函数参数对比

java - gui 中的工具提示未显示?

java - 无法从浏览器访问嵌入式 Glassfish 的运行实例

c - 将字符保存在数组中

c++ - 从父亲到 child 的动态类型转换

c# - 将对象转换为派生类的对象

java - 如何将变量传递给新的 Runnable 声明?

java - java中随机删除数组中的元素