[上下文:Java 新手,4 个月最高; C++ 老手。]
我正在开发一个库,它在很多地方都需要一个固定大小的数组(“固定字符串”)。我正在尝试使用依赖注入(inject) (q.v.) 来解决这个特定问题,所以我想要某种形式的东西:
class Foo
{
private Bar injectedBar;
private char[] injectedFixedString;
Foo(Bar injectedBar, /* what can go here? */ char[5] injectedFixedString);
{ /* initializing code goes here /* }
}
需要简单——这将进入一个自动生成的通信协议(protocol)。我对其派生的协议(protocol)和数据库的控制为零;我将在最终代码中包含数百个(如果不是数千个)此类实例。因此,考虑到所有这些:
是我对 C++ 的唯一选择:
char injectedFixedString[5];
创建自定义类?像这样的东西:
class FixedBarString {
/* could also set this in the constructor, but this complicates code generation a tad */
public static integer STRING_SIZE = 5; /* string size */
char[] fixedString = new char[STRING_SIZE];
FixedBarString(char[] string) throws RuntimeException {
/* check the string here; throw an exception if it's the wrong size.
I don't like constructors that throw however. */
}
public void setString(char[] string) throws RuntimeException {
/* check the string here */
}
public char[] getString() {
/* this isn't actually safe, aka immutable, without returning clone */
}
public char[] createBlankString() {
return new char[STRING_SIZE];
}
}
谢谢。 (如果代码太多,我深表歉意)。
最佳答案
确实没有办法用静态保证的长度做你想做的事,除非你准备为每个长度都有一个新类:FixedBarString4、FixedBarString5 等。(有可能为使用泛型对长度进行编码的单链字符列表创建一个类。但我怀疑您是否愿意在现实世界中使用它。
关于java - 替代 Java 中的固定大小数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4761472/