2

I've read many answers here confirming my (quite obvious) opinions about using enums instead of String objects when dealing with a small, closed sets of values.

But lately I've noticed a couple of examples in the Java API where the opposite choice has been made. I can only remember this one right now

public RandomAccessFile(File file, String mode)

where mode parameter can only be r, rw, rws or rwd. Otherwise, an IllegalArgumentException exception will be thrown.

The only reason I can think of is that such method could be previous to enum introduction in Java language, am I right? If that's true, are there situations today where chosing a String instead of an enum could make any sense for a closed set?

Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48

2 Answers2

5

RandomAccessFile was present as of JDK1.0 whereas enums were introduced in JDK5.0.

tddmonkey
  • 20,798
  • 10
  • 58
  • 67
0

Like @mrwiggles said, Java enum types were introduced as part of the Java 5 release.

If you're curious about why and/or how they improved the language, there are a lot of blogs and examples out there demonstrating their benefits:

In general, if you have a series of specifically predefined values, like you've noted here with r, rw, etc., it's definitely more logical to go with a enum. They are less ambiguous and can be designed much like any other class (containing methods, instance variables, constants, etc). They also can also show minor performance improvements over Strings in some scenarious if they are checked frequently. Read Java: Performance of Enums vs. if-then-else to see exactly what I'm talking about.

Joshua Bloch discusses the benefits of enums over int constants in his book Effective Java. It's not exactly what we're talking about here, but it's pretty close (see More Effective Java with Google's Joshua Bloch):

For enums, the sound bite is "Always use enums in place of int constants" (Item 30). Enums provide so many advantages: compile-time type safety, the ability to add or remove values without breaking clients, meaningful printed values, the ability to associate methods and fields with the values, and so on. Since we have EnumSet, this advice applies equally to bit fields, which should be considered obsolete.

Community
  • 1
  • 1
Mike
  • 522
  • 2
  • 14
  • It's more than clear the improvement to me, I was asking if there was any good reason to use strings instead. (didn't downvote btw...) – Luigi Cortese Dec 06 '15 at 11:40
  • That's okay. It's your right to do so. I probably shouldn't have added that silly part at the end. It's early where I am haha. But let me re-write my answer, I definitely missed what you were asking. – Mike Dec 06 '15 at 11:42
  • OT: I'll come to your side of the world once in life! – Luigi Cortese Dec 06 '15 at 11:43