Home > Java > javaTutorial > How Has the Behavior of `Arrays.asList()` Changed in Java Since Version 1.4.2?

How Has the Behavior of `Arrays.asList()` Changed in Java Since Version 1.4.2?

Patricia Arquette
Release: 2024-12-06 05:36:15
Original
265 people have browsed it

How Has the Behavior of `Arrays.asList()` Changed in Java Since Version 1.4.2?

Arrays to Lists in Java: Evolving Behavior

In Java, converting arrays to lists is a common task. However, the behavior of the Arrays.asList() method has undergone significant changes since Java SE 1.4.2.

Behavior Before Java 1.5

Prior to Java 1.5, Arrays.asList() returned a list containing the actual elements of the array. For example:

int[] numbers = { 1, 2, 3 };
List<Integer> list1 = Arrays.asList(numbers);
Copy after login

In this case, list1 would contain the elements 1, 2, and 3.

Behavior in Java 1.5 and Later

From Java 1.5 onwards, the behavior of Arrays.asList() changed. It now returns a fixed-size list containing a reference to the original array. As a result:

int[] numbers = { 1, 2, 3 };
List<Integer> list2 = Arrays.asList(numbers);
Copy after login

In this case, list2 would contain a single element: the array numbers itself.

Reason for the Change

The change in behavior was made to enforce type safety. Since lists cannot contain primitive types like int, the returned list must be of type List.

Implications for Existing Code

Code written prior to Java 1.5 relying on the old behavior of Arrays.asList() may need to be modified. For example, the following assertion would fail in Java 1.5 and later:

Assert.assertTrue(Arrays.asList(numbers).indexOf(4) == -1);
Copy after login

Converting Arrays to Lists of Primitive Types

To convert an array of primitive types to a list of the corresponding wrapper class, you can use the following technique:

Integer[] numbers = new Integer[] { 1, 2, 3 };
List<Integer> list = Arrays.asList(numbers);
Copy after login

This will create a list of Integer objects containing the values of the array.

The above is the detailed content of How Has the Behavior of `Arrays.asList()` Changed in Java Since Version 1.4.2?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template