Java中固定大小数组的替代选择? [英] Alternative to Fixed-Size Arrays in Java?

查看:65
本文介绍了Java中固定大小数组的替代选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[上下文:Java的新手,顶峰4个月; ]

我正在开发一个库,该库在许多地方都需要固定大小的数组(固定字符串)。我正在尝试对这个特定问题使用依赖注入(qv),所以我想要某种形式的东西:

I'm working on a library that requires an array of a fixed size ("fixed string") in many places. I'm trying to use Dependency Injection (q.v.) for this particular problem, so I would like something of the form:

class Foo 
{
    private Bar injectedBar;
    private char[] injectedFixedString;

    Foo(Bar injectedBar, /* what can go here? */ char[5] injectedFixedString);
    { /* initializing code goes here /* }
}

简单的是必需-这正在进入自动生成的通信协议中。我对衍生自其中的协议和数据库的控制为零;在最终代码中,我将拥有数百个(如果不是数千个)这些实例。因此,鉴于所有这些:

Simple is required -- this is going into an auto-generated communications protocol. I have zero control of the protocol and database it's being derived from; I will have hundreds, if not thousands, of these instances in the final code. So, given all that:

我是C ++的唯一选择:

Is my only alternative to the C++:

char injectedFixedString[5];

创建自定义类?像这样的东西:

to create a custom class? Something like:

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];
    }
}

谢谢。 (如果这是太多的代码,我深表歉意。)

Thanks. (My apologies if this is too much code).

推荐答案

确实没有办法用静态保证的长度,除非您准备为每个长度创建一个新类:FixedBarString4,FixedBarString5等(可以为使用char的单个链接列表创建一个类,该类使用泛型来编码长度。但是我怀疑您是否想在现实世界中使用它。

There is indeed no way to do what you want with a statically guaranteed length, unless you are prepared to have a new class for every length: FixedBarString4, FixedBarString5, etc. (It is possible to create a class for single linked list of chars which uses generics to encode the length. But I doubt you would like to use that in your real world scenario.

这篇关于Java中固定大小数组的替代选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆