Don't use Java Arrays!
Helmut Siegel
?? Senior Java/Angular Engineer | Results-driven Developer | B2B | Freelancer | Consultant | Spring | REST | Jenkins | Docker | AWS
An array is a container that holds a fixed number of values of a single type. Dealing daily with business code, we see how important is to have containers that can hold multiple values. The Java core language offers a possibility for that, and that is the Arrays.
In this article, we will see what are the possibilities of using Java Arrays and what problems can we encounter by using them.
The following class and the instances of it will be used through this article to demonstrate the trials and the tribulations of Java Arrays.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getters, setters and toString omitted for brevity
}
// instantiation
Person elisabeth = new Person("Elisabeth", 30);
Person dave = new Person("Dave", 40);
Person john = Person("John", 35);
1. Create
Creating arrays is quite simple and convenient. Java gives us the following three possibilities to create arrays:
// 1.
Person[] persons = { elisabeth, dave };
// 2.
Person[] persons = new Person[] { elisabeth, dave };
// 3.
Person[] persons = new Person[2];
persons[0] = elisabeth;
persons[1] = dave;
It is obvious that creating an array is not complicated at all. It requires the same effort as creating an instance of any kind of class.
In the following sections, we will see the problematic parts of the arrays.
2. Print
Printing out an array is not as easy as instantiating it.
First of all, we can try to invoke the sysout to see what will be the output:
System.out.println(persons);
// output: [Lmodel.Person;@1b6d3586
It is obvious that is not what we expect. Because the Person class has an overridden toString, we would expect that in the output when printing out.
This is the first problem we have with arrays. They are hard to deal with because it does not have a human-readable toString() method, or another possibility that automatically invokes the toString of the containing values.
领英推荐
If we want to have a human-readable output we have some possibilities and you can see two of them in the following snippet:
// 1.
for(Person p: persons) {
System.out.println(p);
}
//output:
//Person{name='Elisabeth', age=30}
//Person{name='Dave', age=40}
// 2.
System.out.println(Arrays.toString(persons));
//output:
//[Person{name='Elisabeth', age=30}, Person{name='Dave', age=40}]
The java.util.Arrays class was added to Java since version 1.2 and contains various method for manipulating arrays.
Behind the scenes the java.util.Arrays.toString() does something similar to the first printing possibility from the previous snippet.
3. Add
Currently, the persons array has two elements, and we want to add a third one to it.
The first thing that could come to our mind is to do the following, expecting that the element will be added to the end of the array:
persons[2] = john;
// output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at main.Main.main(Main.java:14)
The arrays are not resizable in java, they are fixed-length, which means that if you want to add an element to an array you need to create a new array, copy the elements over and add the new element in place. Let's see the following code snippet:
int length = persons.length;
Person[] newArray = Arrays.copyOf(persons, length + 1);
newArray[length] = john;
4. Business Domain Constraints
With arrays, there is no way to enforce business domain constraints, for example banning duplicates. Java array has no built-in functionalities that can suit our real-world business cases.
Conclusion
Arrays is a low-level programming construct, it is reasonable to have in the core language, but they are not flexible enough for most of the real-world use cases. Using arrays directly in the business code would lead to slow development because of working on custom functionalities that are already implemented in collections.
CTO@Lemin
2 年Do you plan to make a series out of it? E.g. comparing ArrayList, LinkedList etc. with each other?
Staff Software Engineer at Google * Good Person to Know * Autistic * Now on Substack @leemckeeman!
2 年Every rule has exceptions. Building APIs that require arrays as inputs or outputs is probably a bad idea, but there may be instances (as long as you’ve measured it and you are sure) that using an array may be better than “saner” structures. Most obviously, arrays are the basic building block provided by the Java language. If you want to build other data structures that’s what you’ve got. Yes, you can build on top of other existing structures but they will very likely be using arrays (again, always exceptions, like a LinkedList). I think that it is important to know how arrays work, and if you have need for varargs and things they are unavoidable, but know why you’ll get better mileage almost every time using a Collection.