Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java array

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to use Java array". In daily operation, I believe many people have doubts about how to use Java array. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use Java array". Next, please follow the editor to study!

01. What is an array

According to Javadoc, an array is an object that contains a fixed number of elements of the same type. The array puts the elements in the specified location as indexed, which means that we can access them through the index. In Java, the index starts at 0.

We can think of an array as neatly arranged cells, each containing an element.

Array elements can be of either a basic data type (such as int, double) or a reference data type (such as String), including objects of a custom type.

Now that we understand the definition of arrays, let's take a closer look at the use of arrays.

In Java, arrays are declared in two ways.

Let's take a look at the first one:

Int [] anArray

Let's take a look at the second kind:

Int anOtherArray []

The difference is whether the brackets are placed immediately after the type or after the variable name. The former is used more frequently than the latter.

Next, it's time to see how to initialize an array. There are also several ways to initialize an array, such as the most common one:

Int [] anArray = new int [10]

The new keyword is used, right? This means that the array is indeed an object. Then, the length of the array is specified in square brackets, which is necessary.

At this point, each element in the array will be initialized to the default value, and the element of type int will be of type 0 and object of type 0 will be null.

In addition, you can initialize the elements in the array directly using curly braces:

Int anOtherArray [] = new int [] {1,2,3,4,5}

At this point, the elements of the array are 1, 2, 3, 4, 5, and the index is 0, 1, 2, 3, 4, respectively.

02. Access the array

As mentioned earlier, you can access the elements of an array through an index, like this:

AnArray [0] = 10; System.out.println (anArray [0])

Through the variable name of the array, plus parentheses, and the index of the element, you can access the array and assign values through the "=" operator.

If the value of the index exceeds the bounds of the array, an ArrayIndexOutOfBoundException will be thrown. I've written a special article about this, and you can skip it if you're interested.

Why did ArrayIndexOutOfBoundsException happen?

I think the reason is interesting.

Since the index of the array starts at 0, it ends with length-1 of the array. Do not use indexes outside this range to access the array, and you will not throw an exception that crosses the bounds of the array.

03. Traversal array

When the array has a lot of elements, it is too hard to access the array one by one, so it needs to be traversed.

First, use a for loop:

Int anOtherArray [] = new int [] {1,2,3,4,5}; for (int I = 0; I < anOtherArray.length; ionization +) {System.out.println (an OtherArray [I]);}

The length of the array is obtained through the length attribute, and then the index traverses from 0 to get all the elements of the array.

Second, use a for-each loop:

For (int element: anOtherArray) {System.out.println (element);}

If you don't need to care about the index (which means you don't need to modify an element of the array), traversing with for-each is more concise. Of course, you can also use while and do-while loops.

04. Variable parameters

Variable parameters are used to pass any number of parameters to the method:

Void varargsMethod (String... Varargs) {}

The varargsMethod () method can pass any number of string arguments, either 0 or N. In essence, variable parameters are implemented through an array. To prove this, we can decompile the bytecode through jad:

Public class VarargsDemo {public VarargsDemo () {} transient void varargsMethod (String as []) {}}

So we can actually pass the array as a parameter to the method with variable parameters:

VarargsDemo demo = new VarargsDemo (); String [] anArray = new String [] {"Silent King II", "an interesting programmer"}; demo.varargsMethod (anArray)

You can also pass multiple strings directly, separated by commas:

Demo.varargsMethod ("Silence II", "an interesting programmer")

05. Convert the array to List

List encapsulates many commonly used methods to facilitate us to manipulate the collection, but it is inconvenient to manipulate the array directly, so sometimes we need to convert the array to List.

The more primitive way is to add the array to the List one by one by traversing the array.

Int [] anArray = new int [] {1,2,3,4,5}; List aList = new ArrayList (); for (int element: anArray) {aList.add (element);}

A more elegant way is through the asList () method of the Arrays class:

List aList = Arrays.asList (anArray)

Note, however, that the ArrayList returned by this method is not java.util.ArrayList, it is actually an inner class of the Arrays class:

Private static class ArrayList extends AbstractList implements RandomAccess, java.io.Serializable {}

If you need to add or delete an element, it's best to convert it to java.util.ArrayList.

New ArrayList (Arrays.asList (anArray))

06. Convert the array to Stream

Java 8 adds the concept of Stream streams, which means that we can also convert arrays to Stream instead of List.

String [] anArray = new String [] {"Silent King II", "an interesting programmer", "take good care of him"}; Stream aStream = Arrays.stream (anArray)

You can also directly clip the elements of the array by specifying an index:

Stream anotherStream = Arrays.stream (anArray, 1,3)

The results include "an interesting programmer" and "take good care of him". The index position 1 includes, and the index position 3 does not include.

07. Array sorting

The Arrays class provides a sort () method that sorts the array.

The basic data types are arranged in ascending order

The objects of Comparable interface are sorted according to compareTo ().

Let's look at the first example:

Int [] anArray = new int [] {5,2,1,4,8}; Arrays.sort (anArray)

The sorted results are as follows:

[1, 2, 4, 5, 8]

Let's look at the second example:

String [] yetAnotherArray = new String [] {"A", "E", "Z", "B", "C"}; Arrays.sort (yetAnotherArray, 1,3, Comparator.comparing (String::toString). Reversed ())

Reverse only the elements at positions 1-3, so the result is as follows:

[A, Z, E, B, C]

08, array search

Sometimes, we need to find a specific element from the array, and the more direct way is by traversing:

Int [] anArray = new int [] {5,2,1,4,8}; for (int I = 0; I < anArray.length; iTunes +) {if (anArray [I] = = 4) {System.out.println ("found" + I); break;}}

In the above example, element 4 is queried from the array, and the loop is exited with the break keyword after finding it.

If the array is sorted in advance, you can use binary lookup, which makes it more efficient. The Arrays.binarySearch () method is available to us, which needs to pass an array and the elements to find.

Int [] anArray = new int [] {1, 2, 3, 4, 5}; int index = Arrays.binarySearch (anArray, 4); at this point, the study on "how to use the Java array" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report