Try to avoid using array _java in Java interfaces

Source: Internet
Author: User
Tags data structures

If you find that an interface is used with the following definition method:

Public string[] GetParameters ();

Then you should seriously reflect. Arrays are not just old-fashioned, and we have reasonable grounds to avoid exposing them. In this article, I will try to summarize the pitfalls of using arrays in the Java API. Let's start with one of the most surprising examples.
array causes poor performance

You might think that using arrays is the quickest because arrays are the underlying data structures that most collection implementations. How can using a pure array be less performance than using an object that contains an array?


Let's start with a common idiom that looks familiar:

Public string[] GetNames () {return
 Nameslist.toarray (new string[nameslist.size ());
}

This method creates a data from a mutable collection that is used to hold data inside it. It attempts to optimize the creation of an array by providing an array of exact sizes. Interestingly, this "optimization" makes it slower than the simpler version below (see the Green vs Orange bar in the chart):

Public string[] GetNames () {return
 nameslist.toarray (new string[0]);

However, if the method returns a list, creating a defensive copy is faster (red bar):

Public list<string> GetNames () {return
 new ArrayList (nameslist);
}

The difference is that a ArrayList puts its data items in a object[] array and uses the ToArray method of no type, which is much faster than the type method (blue bar). This is type-safe because an array of no types 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 case system, this picture does not change too much. The CPU overhead may not be too drastic, but there will be growth. The user of an array should convert it to a set so that it can be used to do anything, and then convert the result back to an array to send into the method of another interface, and so forth.

is to use a simple ArrayList instead of an array to improve performance without moving too many hands and feet. ArrayList adds a constant cost of 32 bytes to the encapsulated array. For example, an array with 10 objects requires 104 bytes and a ArrayList of 136 bytes.

With a collection, you may even decide to return an unmodified version of the internal list:

Public list<string> GetNames () {return
 collections.unmodifiablelist (nameslist);
}

This operation will run at a fixed market price, so he is much faster than any of the other methods mentioned above (Huang). It is different from the same defensive copy. A set that cannot be modified will change as your internal data changes. If the change occurs, the client will run into a concurrentmodificationexception when iterating over the data item. You can think of it as a bad design, and the interface provides a unsupportedoperationexception at run time. However, at least for internal use, this method is a high-performance choice for a defensive copy-something that cannot be implemented using arrays.

Array defines a struct, not an interface

Java is an object-oriented language. The core object-oriented concept is to provide methods to access and manipulate their data, rather than directly manipulating data fields. These methods create an interface to describe what you can do on the object.

Because Java has been designed for performance, native types and arrays have been integrated into the type system. objects can use arrays to store data efficiently in content. However, even though arrays are used to render elements of a mutable collection, they do not provide any way to access and manipulate these elements. In fact, you don't have a lot of other things to do on an array other than directly accessing the replacement element. Arrays do not even have a meaningful implementation of ToString and equals, but collections have:

String[] array = {"Foo", "Bar"};
list<string> list = arrays.aslist (array);
 
SYSTEM.OUT.PRINTLN (list);
-> [foo, bar]
System.out.println (array);
-> [ljava.lang.string;@6f548414
 
list.equals (arrays.aslist ("foo", "Bar"))
//-> true
Array.equals (new string[] {"foo", "Bar"})
//-> false

Unlike arrays, the collection API provides a number of useful ways to access elements. The user can examine the contained elements, extract the child list, or compute the intersection. Collections can add specific attributes to the data tier, such as thread safety, while keeping the implementation principle internally visible.

By using a single data, you define where the data is stored in memory. By using a collection, you define what the user can do with the data.

Array is not type-safe

If you depend on the type safety of the compiler check, be careful with the object array. The following code will crash at run time, but the compiler can't find the problem:

number[] numbers = new INTEGER[10];
Numbers[0] = long.valueof (0); 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 its book effective Java covers all the theories that every Java developer must read.

Due to this behavior, an interface that exposes an array type allows the return of a subtype of the declared array type, resulting in a bizarre run-time exception.


Bloch also explains that the array is incompatible with the generic type. Because the array enforces the type information at run time, the generics are checked at compile time and the generic type cannot be placed in the array.

    • In general, arrays and generics do not blend well. If you find yourself fusing them with a compile-time error or warning, your first reaction should be to replace the array with the list.

-Joshua Bloch, effective Java (second edition), 29th
Summary

The language constructs at the bottom of the array, they are used in the implementation, but they should not be exposed to other classes. Using arrays in an interface method violates the object-oriented principle, which can cause Shong APIs, and it can also cause a short board for type safety and performance.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.