java - 替代 Java 中的固定大小数组?

标签 java c++ arrays fixed-width

[上下文: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/

相关文章:

javascript - 如何使用数组中的名称生成标记表并在旁边显示文本框?

ruby - 按降序对字符串数组进行排序

arrays - MATLAB:将值映射到其他数组的索引

java - 在 Spring AMQP 中处理无法传递给消费者的消息

java - 如何修复 Web 应用程序中的 session 固定问题

java - 如何在CXF中处理来自外部系统的SOAP故障?

c# - 在程序中运行 gcc 的安全、跨平台方式

c++ - 开关(event.type)不工作并且计时器不显示

java - Wsimport 在 Java 11 中失败

c++ - 从文件读取后输出中有额外的零行