How to get the Java array length?

In Java:


In Clojure:

(.. java.awt.GraphicsEnvironment
Execution error (IllegalArgumentException) at user/eval175 (REPL:1).
No matching field found: length for class [Ljava.lang.String;

So I’m using count instead of length:

(-> java.awt.GraphicsEnvironment
     (. getLocalGraphicsEnvironment) 

But I’m intrigued:

  1. Why doesn’t [Ljava.lang.String have a length attribute?
  2. Will count transverse the Array?

See and

Thank you.

So it will not transverse the Array and alenght function will give me the “Array lenght” value.


Yup, you can see the explanation here

Arrays don’t really have a length field, its Java syntax sugar. Since arrays are primitive types and not real objects.


Thank you.

I wonder how does this affect other JVM languages.

I think Kotlin and Scala do the same thing as Java. I think they can do that because it can tell at compile time that it’s an array, and compile to the right byte code I suppose.

Groovy seems to force you to similarly annotate the type of the variable as being an array for it to work, and then you can use the size() method over it.

So maybe in Clojure, similar support could be added so if one type hints it as an array length could be used. Actually, maybe you could try that? Maybe it already exists.

Anyways, from my small research, it seems other JVM languages handle it at compile time by special handling of known arrays whose type must be declared at compile time.


Meeting the myth half-way, with a compiler error message that mentions alength, was suggested in back in 2014 and declined.

The matter came up again in 2019 on the Google Group, where Alex Miller shared some of his thinking about why the suggestion is difficult to embrace.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.