Home Java javaTutorial [java tutorial] Java array

[java tutorial] Java array

Dec 26, 2016 pm 01:22 PM
java array

Java Arrays

Arrays are one of the important data structures for every editing language. Of course, different languages ​​implement and process arrays differently.

Arrays provided in the Java language are used to store fixed-size elements of the same type.

You can declare an array variable, such as numbers[100] instead of directly declaring 100 independent variables number0, number1, ...., number99.

This tutorial will introduce you to the declaration, creation and initialization of Java arrays, and give you the corresponding code.

Declare array variables

Array variables must first be declared before the array can be used in the program. The following is the syntax for declaring array variables:

dataType[] arrayRefVar;   // 首选的方法

或

dataType arrayRefVar[];  // 效果相同,但不是首选方法
Copy after login

Note: It is recommended to use the declaration style of dataType[] arrayRefVar to declare array variables. The dataType arrayRefVar[] style comes from the C/C++ language and is adopted in Java to allow C/C++ programs to quickly understand the java language.

Examples

The following are code examples of these two syntaxes:

double[] myList;         // 首选的方法

或

double myList[];         //  效果相同,但不是首选方法
Copy after login

Create arrays

Java language uses the new operator to create arrays. The syntax is as follows :

arrayRefVar = new dataType[arraySize];
Copy after login

The above syntax statement does two things:

1. Use dataType[arraySize] to create an array.

2. Assign the reference of the newly created array to the variable arrayRefVar.

The declaration of array variables and the creation of an array can be completed in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];
Copy after login

In addition, you can also create an array in the following way.

dataType[] arrayRefVar = {value0, value1, ..., valuek};
Copy after login

The elements of an array are accessed by index. Array indexing starts at 0, so index values ​​range from 0 to arrayRefVar.length-1.

Example

The following statement first declares an array variable myList, then creates an array containing 10 double type elements, and assigns its reference to the myList variable.

double[] myList = new double[10];
Copy after login

The picture below depicts the array myList. Here, there are 10 double elements in the myList array, and their subscripts range from 0 to 9.

[java tutorial] Java array

Processing Arrays

The element type of the array and the size of the array are determined, so when processing array elements, we usually use a basic loop or foreach cycle.

Example

This example completely demonstrates how to create, initialize and manipulate an array:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // 打印所有数组元素
      for (int i = 0; i < myList.length; i++) {
         System.out.println(myList[i] + " ");
      }
      // 计算所有元素的总和
      double total = 0;
      for (int i = 0; i < myList.length; i++) {
         total += myList[i];
      }
      System.out.println("Total is " + total);
      // 查找最大元素
      double max = myList[0];
      for (int i = 1; i < myList.length; i++) {
         if (myList[i] > max) max = myList[i];
      }
      System.out.println("Max is " + max);
   }
}
Copy after login

The above example compiles and runs and the results are as follows:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Copy after login

foreach loop

JDK 1.5 introduces a new type of loop, called a foreach loop or enhanced loop, which can traverse an array without using subscripts.

Example

This example is used to display all elements in the array myList:

public class TestArray {

   public static void main(String[] args) {
      double[] myList = {1.9, 2.9, 3.4, 3.5};

      // 打印所有数组元素
      for (double element: myList) {
         System.out.println(element);
      }
   }
}
Copy after login

The compilation and running results of the above example are as follows:

1.9
2.9
3.4
3.5
Copy after login

数组作为函数的参数

数组可以作为参数传递给方法。例如,下面的例子就是一个打印int数组中元素的方法。

public static void printArray(int[] array) {
  for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
  }
}
Copy after login

下面例子调用printArray方法打印出 3,1,2,6,4和2:

printArray(new int[]{3, 1, 2, 6, 4, 2});
Copy after login



数组作为函数的返回值

public static int[] reverse(int[] list) {
  int[] result = new int[list.length];

  for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
    result[j] = list[i];
  }
  return result;
}
Copy after login

以上实例中result数组作为函数的返回值。


Arrays 类

java.util.Arrays类能方便地操作数组,它提供的所有方法都是静态的。具有以下功能:

给数组赋值:通过fill方法。

对数组排序:通过sort方法,按升序。

比较数组:通过equals方法比较数组中元素值是否相等。

查找数组元素:通过binarySearch方法能对排序好的数组进行二分查找法操作。

具体说明请查看下表:

序号

方法和说明

1    public static int binarySearch(Object[] a, Object key)
用二分查找算法在给定数组中搜索给定值的对象(Byte,Int,double等)。数组在调用前必须排序好的。如果查找值包含在数组中,则返回搜索键的索引;否则返回 (-(插入点) - 1)。    

2    public static boolean equals(long[] a, long[] a2)
如果两个指定的 long 型数组彼此相等,则返回 true。如果两个数组包含相同数量的元素,并且两个数组中的所有相应元素对都是相等的,则认为这两个数组是相等的。换句话说,如果两个数组以相同顺序包含相同的元素,则两个数组是相等的。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。    

3    public static void fill(int[] a, int val)
将指定的 int 值分配给指定 int 型数组指定范围中的每个元素。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。    

4    public static void sort(Object[] a)
对指定对象数组根据其元素的自然顺序进行升序排列。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。    

 以上就是【java教程】Java 数组的内容,更多相关内容请关注PHP中文网(www.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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles