gpt4 book ai didi

java - 初始化静态列表中对象的最简洁方法

转载 作者:行者123 更新时间:2023-12-01 16:47:20 26 4
gpt4 key购买 nike

我正在学习 Java,之前学过 C 和 C#,想知道是否没有比下面所示的更简洁的方法来初始化对象的静态列表?

对于本质上是一个简单的结构类型,创建并重复使用 Part 的构造函数似乎很麻烦。

class Widget {

private static class Part {
public String number;
public String description;

Part(String number, String description)
{
// a constructor just to initialize public fields? ugh
this.number = number;
this.description = description;
}
}

private static final List<Part> parts = List.of(
new Part("ABC", "Doo-hickey"), // < seems overwrought
new Part("DEF", "whadjamacalit"),
new Part("HIJ", "thing-a-ma-bob"),
// ...
);

// ...
}

最佳答案

I'm learning Java, coming from C and C#, and wondering if there is not a more succinct way to initialize a static list of objects than is shown below?

还有一些类似冗长的替代方案,但因为您的主要反对意见似乎是使用 new运算符和类名的重复,不,没有办法避免这些或等价物。特别是,对于复合类型的对象,Java 没有直接类似 C 风格的初始值设定项。

您会注意到,我为“等效项”留下了一些回旋余地,而不是专门使用 new和一个构造函数。事实上所需要的只是一个可以在静态上下文中计算的适当类型的表达式。使用 new 的最显着的替代方案运算符将是对合适的静态方法的调用或对静态可访问对象的实例方法的调用。

Seems like a lot of bother to go to, creating and repeatedly using the constructor of Part, for what is essentially a simple struct type.

Java 不以这种方式区分不同类型的引用类型。事实上,尽管您没有为您的类定义任何方法 Part ,它仍然具有从 Object 继承的那些,从这个意义上说,它并不类似于我认为你所说的“简单结构类型”。

另请注意 List<Part>可以包含 Part 子类的实例,因此从 Java 编译器的本地化角度来看,并不清楚每个元素都应该专门属于 Part 类。 。 Java 可以将其视为一种假设,但不这样做更简单。从我的角度来看,这几个额外的字符没什么大不了的。

关于java - 初始化静态列表中对象的最简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47891128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com