I have often thought it would be a good idea to allow the use of arrays as proper objects with their own methods instead of relying on helper classes like Arrays, Arrays and ArrayUtils.
For example:
ints.sort(); // Arrays.sort(ints); int[] onemore = ints.add(8); // int[] onemore = ArrayUtils.add(ints, 8);
I am sure I am not the first with this idea but I have had trouble searching for others who have written about this before. Can anyone help me with some references on this topic?
Is this thought to be a good or bad idea, and why?
How easy would this be to implement?
Some other examples might include (but don’t get hung up on them, they’re extraneous to the question itself):
int[] ints = {5,4,3,2,1}; // Arrays.sort (ints); ints.sort(); // int pos = Arrays.asList(ints).indexOf (5); // int pos = ArraysUtils.indexOf (ints, 5); int pos = ints.indexOf (5); // Arrays.reverse (ints); ints.reverse(); Array<Integer> array = ints; // cast to super class. // int length = Array.getLength (array); int length = array.getLength(); // Object n = Array.get (array, 3); Object n = array.get (3); // Array.set (array, 3, 7); array.set (3, 7); Object obj = array; // if (obj instanceof int[]) // System.out.println(Array.toString((int[]) obj)); // else if (....) System.out.println (obj);
Arrays are not classes in Java for a good reason – they map well onto people’s understanding of how an array should work from experience with C-style languages. There are also performance reasons for making arrays low-level containers rather than objects. Because of this, sometimes there are performance benefits to using a primitive array rather than a Collection.
If you want to use objects, you should just use a Collection (an ArrayList is an example of a collection). It can be clunky, but Collections provide the type of nice methodological access that you seem to want.