Alternative to fixed size arrays in Java?

[Context: new for Java, 4 months; old hand in C ++.]

I am working on a library that requires a fixed-size array ("fixed string") in many places. I am trying to use Dependency Injection (qv) for this specific problem, so I would like something like a form:

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

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

A simple one is required - this happens in an automatically generated communication protocol. I have zero control over the protocol and the database from which it is derived; I will have hundreds, if not thousands, of these instances in the final code. So, considering all this:

I am the only C ++ alternative:

char injectedFixedString[5];

create custom class? Sort of:

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

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

+3
4

, , , : FixedBarString4, FixedBarString5 .. ( , . , .

+2

100% , . ? ? ?

bean validation, :

Foo(Bar injectedBar, @Size(min=5,max=5) char[] injectedFixedString)
+2

It is impossible to use java.lang.Stringjava in the program and convert it only to an array if necessary. Using toCharArray()and restricting the line to this (using StringUtils.right(str, 5)from commons-lang, for example)

Or you can throw IllegalArgumentExceptionit when a string with a length of more than 5 is passed to the method.

+1
source

You may have

Foo(Bar injectedBar, char[] injectedFixedString)

and name him

new Foo(injectedBar, new char[5])

or

Foo(Bar injectedBar, fixedStringLength)
new Foo(injectedBar, 5)

It is also worth noting that char is 2 bytes, not one. your protocol assumes 16-bit characters or 8-bits.

0
source

Source: https://habr.com/ru/post/1786965/


All Articles