Why do Java libraries use constant ints more than enums?

I'm not sure this is the final statement, but it seems to me that the Java API prefers persistent ints over enums. Of the parts of the API that I used, I came across a lot of final static int constants, where you could use instead of enum . Someday such an example that I am looking at this moment:

From java.awt.BasicStroke :

 public final static int CAP_BUTT = 0; public final static int CAP_ROUND = 1; public final static int CAP_SQUARE = 2; 

Actually, I don’t think I have ever seen an enumeration used in the standard Java API class. Why is this?

I am developing an API for my own application (about a billion times smaller than the Java API, but I'm still trying to be smart) and trying to decide whether to use constant ints or enums. THIS publishes links to a very popular book that I have not read yet, which means that listings have many advantages. Most other high-level answers in the same topic agree. So why doesn't Java seem to use its own enumeration capabilities?

+7
source share
2 answers

BasicStroke pre- enum dates that appeared in Java 1.5. The code is left as is for backward compatibility. When writing any new code, enums is by far the best design choice over final static variables.

+13
source

This is not because the int constant is better than enum: it's just that the enum was only added in JDK 5, so most of the java API was written before the enum was available: constant ints were the only option, so there were used.

If the java API has been rewritten, it will contain much more enumerations, and you can expect them to appear in new additions to the API in JDK6 or later.

You should probably use enumerations for your application, they are usually the best option.

+11
source

All Articles