How to get the Java array length?

In Java:

java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames().length

In Clojure:

(.. java.awt.GraphicsEnvironment
    getLocalGraphicsEnvironment
    getAvailableFontFamilyNames
    length)
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) 
     .getAvailableFontFamilyNames
     count)

But I’m intrigued:

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

See https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/RT.java#L668 and https://clojuredocs.org/clojure.core/alength

Thank you.

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

Good.

Yup, you can see the explanation here https://stackoverflow.com/a/54273982/172272

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

2 Likes

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.

2 Likes

Meeting the myth half-way, with a compiler error message that mentions alength, was suggested in https://clojure.atlassian.net/browse/CLJ-1448 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