Reprint: http://eclipsesource.com/blogs/2014/04/11/3-good-reasons-to-avoid-arrays-in-java-interfaces/
If you find that the use of an interface has the following definition method:
Public string[] GetParameters ();
Then you should seriously reflect on it. Arrays are not just old-fashioned, and we have reasonable reasons to avoid exposing them. In this article, I'll try to summarize the pitfalls of using arrays in the Java API. Let's start with one of the most surprising examples.
Arrays cause poor performance
You might think that using arrays is the quickest, because arrays are the underlying data structures that most collection implement. How can using a pure array be less performance than using an object that contains an array?
Let's start with a general idiom that looks familiar:
Public string[] GetNames () { returnnew string[nameslist.size ()]);}
This method creates a data from a mutable collection that is used to store data inside it. It attempts to optimize the creation of arrays by providing an array of the exact size. Interestingly, this "optimization" makes it slower than the simpler version below (see Green vs Orange bars in the chart):
Public string[] GetNames () { returnnew string[0 ]);}
However, if the method returns a list, creating a defensive copy is much faster (red stripe):
Public List<string> GetNames () { returnnew ArrayList (nameslist);}
The difference is that a ArrayList puts its data items in an object[] array, and uses the untyped ToArray method, which is much faster than a type method (blue bar). This is type-safe because an untyped array is encapsulated in a generic type arraylist<t> that is checked by the compiler.
This icon shows a reference standard for n=5 on Java 7. However, more data items or a different VM condition, this picture does not change too much. The overhead of the CPU may not be too drastic, but there will be growth. Chances are that the user of an array should convert it to a collection to use it to do anything, and then convert the result back to an array, to send it to another interface, and so forth.
Use a simple array list instead of an array that can improve performance without too much rushing. The array list adds a continuous 32-byte overhead to the wrapped array. For example, an array of ten objects requires 104 bytes, and an array list has 136 bytes. Using the collection, you can even decide to return a non-modifiable version of the internal list:
public list<string>getnames () return collections.unmodifiablelist ( NameList);}
This is done within a constant time, so it is much faster than any of the above (yellow bars). This is not the same as the standby copy. When your internal database changes, you can change a non-modifiable collection. If this happens, Customers can run concurrentmodificationexception. When iterating over this project, it may be considered an unfriendly interface that provides a way to throw unsupportoperationexception at runtime. However, at least for internal use, this method may be a high-performance solution for a standby replica-using arrays, which is not possible
An array defines a structure, not an interface
Java is an object-oriented language. The core concept of object-oriented is to provide some methods to access and manipulate their data, instead of directly manipulating data fields. These methods create an interface that describes what you can do on the object.
Since Java has already designed the performance, native types and arrays have been fused into the type system. objects can use arrays to store data efficiently in content. However, even if you render an element of a mutable collection through an array, they do not provide any way to access and manipulate those elements. In fact, you don't have much else to do with the array, except for the replacement elements that are accessed directly. Arrays do not even have a meaningful implementation of both ToString and equals, but the collection has:
String[] array = {"Foo", "Bar" }; List<String> list = arrays.aslist (array); SYSTEM.OUT.PRINTLN (list); // --[foo, bar] System.out.println (array); // (ljava.lang.string;@6f548414"foo", "Bar" )) // - true New String[] {"foo", "Bar" })// - false
Unlike arrays, the collection's API provides a number of useful ways to access elements. The user can examine the contained elements, extract the sub-lists, or calculate the intersection. Collections can add specific attributes to the data layer, such as thread safety, while keeping the implementation principle internally visible.
By using one data, you define where the data is stored in memory. By using a collection, you define the actions that the user can make on the data.
Array is not type-safe
If you rely on compiler checking for type safety, be careful with object arrays. The following code crashes at run time, but the compiler doesn't find the problem:
New integer[10];numbers[// throws Arraystoreexception
The reason is that the array is "covariant", for example, if T is a subtype of S, then t[] is a subtype of s[]. Joshua Bloch in his writings effective Java covers all the theories that every Java developer must read.
Attributed to this behavior, exposing an array-type interface allows returning a subtype of the declared array type, resulting in a weird run-time exception.
Bloch also explains that arrays are incompatible with generic types. Because the array enforces type information at run time, generics are checked at compile time and generic types cannot be placed in arrays.
Generally, arrays and generics do not converge well. If you find yourself merging them and getting a compile-time error or warning, your first reaction should be to replace the array with a list.
-Joshua Bloch, effective Java (second edition), 29th
Summarize
The underlying language constructs of the arrays, they are used in implementations, but they should not be exposed to other classes. Using an array in an interface method violates the object-oriented principle, which results in the vainly disobey API, and it can also cause a short board for type safety and performance.
3 reasons to avoid using arrays in the Java+ interface