Search code examples
javaarraysooplanguage-designstatic-methods

Does Java's Arrays.asList() violate OOP?


In Java, I wanted to convert an array to a list. Given that Java is an OOP language I expected to do something like:

int[] myArray = { 1, 2, 3 };               // non-working code
List myList = myArray.toList();

but was surprised when I found the array object doesn't have a toList method and the correct way to do what I wanted was:

int[] myArray = { 1, 2, 3 };               // working Java code
List myList = Arrays.asList(myArray);

At first I wondered if an int[] was not considered an object but I was able to call methods such as clone() on it, so I am sure it is an object.

Why did the designers of Java use the second approach (static method inconsistent with OOP) versus the first approach (opperate on an object consistent with OOP principles)?

I've noticed C++ does stuff like the second approach too which I have assumed was baggage left over from C. But in C#, there is a ToList() method.

Is the Arrays.asList() just a hold out on the evolutionary march towards OOP or was there some underlying theory to do it this way?


Solution

  • Arrays (int[], Foo[]) were present in Java from the first version (JDK1.0). There was very little support for data structures - you had to do it all yourself. List and ArrayList and Arrays were introduced in V1.2 (http://docs.oracle.com/javase/6/ocs/api/java/util/List.html ). It's possible that when that occurred it wasn't possible to change the language or that it was too complex at the time.

    I was a close observer of the early days of Java (through Sun contacts). I remember that Java 1.0 was fairly basic and the graphics (AWT 1.02) was written at the last moment. In my recollection Java was designed as OO but had initially limited scope (It was hyped as a new animation language, but Java AWT 1.02 was very limiting). There are artefacts from that period still resident in the spec.

    The massive contribution of Java at that time was WriteOnceRunAnywhere (WORA) (initially WriteOnceDebugEverywhere!) and I suspect that that was the prime consideration in early developers and maintainers. Java was informed by C++ and carried some of the constructs (e.g. int, double as primitives - autoboxing came later as a kludge). C# was able to start from Java (rather than C++) and is in some ways a revision of how Java should be. All languages start with some baggage and each new one gets rid of some.