如何在java中声明和初始化数组?

krcsximq  于 2021-07-12  发布在  Java
关注(0)|答案(28)|浏览(570)

如何在java中声明和初始化数组?

xt0899hw

xt0899hw1#

声明数组: int[] arr; 初始化数组: int[] arr = new int[10]; 10表示数组中允许的元素数
声明多维

ubbxdtey

ubbxdtey2#

数组可以包含基元数据类型以及类的对象,具体取决于数组的定义。对于基本数据类型,实际值存储在连续的内存位置。对于类的对象,实际对象存储在堆段中。

一维数组:
一维数组声明的一般形式是

type var-name[];
OR
type[] var-name;

用java示例化数组

var-name = new type [size];

例如,

int intArray[];  // Declaring an array
intArray = new int[20];  // Allocating memory to the array

// The below line is equal to line1 + line2
int[] intArray = new int[20]; // Combining both statements in one
int[] intArray = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// Accessing the elements of the specified array
for (int i = 0; i < intArray.length; i++)
    System.out.println("Element at index " + i + ": "+ intArray[i]);

参考:java中的数组

epfja78i

epfja78i3#

另一个完整的例子是电影课:

public class A {

    public static void main(String[] args) {

        class Movie {

            String movieName;
            String genre;
            String movieType;
            String year;
            String ageRating;
            String rating;

            public Movie(String [] str)
            {
                this.movieName = str[0];
                this.genre = str[1];
                this.movieType = str[2];
                this.year = str[3];
                this.ageRating = str[4];
                this.rating = str[5];
            }
        }

        String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};

        Movie mv = new Movie(movieDetailArr);

        System.out.println("Movie Name: "+ mv.movieName);
        System.out.println("Movie genre: "+ mv.genre);
        System.out.println("Movie type: "+ mv.movieType);
        System.out.println("Movie year: "+ mv.year);
        System.out.println("Movie age : "+ mv.ageRating);
        System.out.println("Movie  rating: "+ mv.rating);
    }
}
cpjpxq1n

cpjpxq1n4#

数组是项的顺序列表

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =
{
  { value, value, value, .. value },
  { value, value, value, .. value },
    ..     ..     ..        ..
  { value, value, value, .. value }
};

如果它是一个物体,那么它就是同一个概念

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =
{
  { new Object(), new Object(), .. new Object() },
  { new Object(), new Object(), .. new Object() },
    ..            ..               ..
  { new Object(), new Object(), .. new Object() }
};

对于对象,需要将其指定给 null 使用 new Type(..) ,类,如 String 以及 Integer 特殊情况将按以下方式处理

String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };

通常,您可以创建 M 维度的

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;

值得注意的是 M 多维数组在空间上是昂贵的。从你创建一个 M 二维数组 N 在所有维度上,数组的总大小都大于 N^M ,因为每个数组都有一个引用,在m维上有一个(m-1)维的引用数组。总尺寸如下

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data
rkue9o1l

rkue9o1l5#

package com.examplehub.basics;

import java.util.Arrays;

public class Array {

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        /*
         * numbers[0] = 1
         * numbers[1] = 2
         * numbers[2] = 3
         * numbers[3] = 4
         * numbers[4] = 5
         */
        System.out.println("numbers[0] = " + numbers[0]);
        System.out.println("numbers[1] = " + numbers[1]);
        System.out.println("numbers[2] = " + numbers[2]);
        System.out.println("numbers[3] = " + numbers[3]);
        System.out.println("numbers[4] = " + numbers[4]);

        /*
         * Array index is out of bounds
         */
        //System.out.println(numbers[-1]);
        //System.out.println(numbers[5]);

        /*
         * numbers[0] = 1
         * numbers[1] = 2
         * numbers[2] = 3
         * numbers[3] = 4
         * numbers[4] = 5
         */
        for (int i = 0; i < 5; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        /*
         * Length of numbers = 5
         */
        System.out.println("length of numbers = " + numbers.length);

        /*
         * numbers[0] = 1
         * numbers[1] = 2
         * numbers[2] = 3
         * numbers[3] = 4
         * numbers[4] = 5
         */
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        /*
         * numbers[4] = 5
         * numbers[3] = 4
         * numbers[2] = 3
         * numbers[1] = 2
         * numbers[0] = 1
         */
        for (int i = numbers.length - 1; i >= 0; i--) {
            System.out.println("numbers[" + i + "] = " + numbers[i]);
        }

        /*
         * 12345
         */
        for (int number : numbers) {
            System.out.print(number);
        }
        System.out.println();

        /*
         * [1, 2, 3, 4, 5]
         */
        System.out.println(Arrays.toString(numbers));

        String[] company = {"Google", "Facebook", "Amazon", "Microsoft"};

        /*
         * company[0] = Google
         * company[1] = Facebook
         * company[2] = Amazon
         * company[3] = Microsoft
         */
        for (int i = 0; i < company.length; i++) {
            System.out.println("company[" + i + "] = " + company[i]);
        }

        /*
         * Google
         * Facebook
         * Amazon
         * Microsoft
         */
        for (String c : company) {
            System.out.println(c);
        }

        /*
         * [Google, Facebook, Amazon, Microsoft]
         */
        System.out.println(Arrays.toString(company));

        int[][] twoDimensionalNumbers = {
                {1, 2, 3},
                {4, 5, 6, 7},
                {8, 9},
                {10, 11, 12, 13, 14, 15}
        };

        /*
         * total rows  = 4
         */
        System.out.println("total rows  = " + twoDimensionalNumbers.length);

        /*
         * row 0 length = 3
         * row 1 length = 4
         * row 2 length = 2
         * row 3 length = 6
         */
        for (int i = 0; i < twoDimensionalNumbers.length; i++) {
            System.out.println("row " + i + " length = " + twoDimensionalNumbers[i].length);
        }

        /*
         * row 0 = 1 2 3
         * row 1 = 4 5 6 7
         * row 2 = 8 9
         * row 3 = 10 11 12 13 14 15
         */
        for (int i = 0; i < twoDimensionalNumbers.length; i++) {
            System.out.print("row " + i + " = ");
            for (int j = 0; j < twoDimensionalNumbers[i].length; j++) {
                System.out.print(twoDimensionalNumbers[i][j] + " ");
            }
            System.out.println();
        }

        /*
         * row 0 = [1, 2, 3]
         * row 1 = [4, 5, 6, 7]
         * row 2 = [8, 9]
         * row 3 = [10, 11, 12, 13, 14, 15]
         */
        for (int i = 0; i < twoDimensionalNumbers.length; i++) {
            System.out.println("row " + i + " = " + Arrays.toString(twoDimensionalNumbers[i]));
        }

        /*
         * 1 2 3
         * 4 5 6 7
         * 8 9
         * 10 11 12 13 14 15
         */
        for (int[] ints : twoDimensionalNumbers) {
            for (int num : ints) {
                System.out.print(num + " ");
            }
            System.out.println();
        }

        /*
         * [1, 2, 3]
         * [4, 5, 6, 7]
         * [8, 9]
         * [10, 11, 12, 13, 14, 15]
         */
        for (int[] ints : twoDimensionalNumbers) {
            System.out.println(Arrays.toString(ints));
        }

        int length = 5;
        int[] array = new int[length];
        for (int i = 0; i < 5; i++) {
            array[i] = i + 1;
        }

        /*
         * [1, 2, 3, 4, 5]
         */
        System.out.println(Arrays.toString(array));

    }
}

来源于examplehub/java

aij0ehis

aij0ehis6#

String[] colors;
    String[] cars = {"red", "blue", "green", "gray"};
    System.out.println(colors[0]);
    colors[0] = "pink";

Also to create a two-dimensional array, add each array within its own set of 
curly braces:

    int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

    int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
    int x = myNumbers[1][2];

You can also use a for loop inside another for loop to get the elements of a 
two-dimensional array: 
    for (int i = 0; i < myNumbers.length; ++i) {
          for(int j = 0; j < myNumbers[i].length; ++j) {
            System.out.println(myNumbers[i][j]);
          }
        }
xzv2uavs

xzv2uavs7#

int[] x = new int[enter the size of array here];

例子:

int[] x = new int[10];

int[] x = {enter the elements of array here];

例子:

int[] x = {10, 65, 40, 5, 48, 31};
jslywgbw

jslywgbw8#

使用局部变量类型推断,只需指定一次类型:

var values = new int[] { 1, 2, 3 };

int[] values = { 1, 2, 3 }
izkcnapc

izkcnapc9#

数组有两种基本类型。
静态数组:固定大小的数组(其大小应在开始时声明,以后不能更改)
动态数组:不考虑大小限制(纯动态数组在java中不存在。相反,最受鼓励的做法是列出清单。)
要声明整数、字符串、浮点等的静态数组,请使用下面的声明和初始化语句。

int[] intArray = new int[10];
String[] intArray = new int[10];
float[] intArray = new int[10];

// Here you have 10 index starting from 0 to 9

要使用动态功能,必须使用列表。。。列表是纯动态数组,不需要在开始时声明大小。下面是用java声明列表的正确方法-

ArrayList<String> myArray = new ArrayList<String>();
myArray.add("Value 1: something");
myArray.add("Value 2: something more");
p5cysglq

p5cysglq10#

这里有很多答案。我添加了一些技巧性的方法来创建数组(从考试的Angular 来看,知道这一点很好)
声明和定义数组

int intArray[] = new int[3];

这将创建一个长度为3的数组。由于它包含一个基元类型int,所以默认情况下所有值都设置为0。例如,

intArray[2]; // Will return 0

在变量名前使用方括号[]

int[] intArray = new int[3];
intArray[0] = 1;  // Array content is now {1, 0, 0}

初始化并向数组提供数据

int[] intArray = new int[]{1, 2, 3};

这一次没有任何必要提及框中括号的大小。即使是一个简单的变体:

int[] intArray = {1, 2, 3, 4};

长度为0的数组

int[] intArray = new int[0];
int length = intArray.length; // Will return length 0

类似于多维数组

int intArray[][] = new int[2][3];
// This will create an array of length 2 and
//each element contains another array of length 3.
// { {0,0,0},{0,0,0} }
int lenght1 = intArray.length; // Will return 2
int length2 = intArray[0].length; // Will return 3

在变量前使用方括号:

int[][] intArray = new int[2][3];

如果你在最后放一个框式支架,那绝对没问题:

int[] intArray [] = new int[2][4];
    int[] intArray[][] = new int[2][3][4]

一些例子

int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
    int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
    int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
    // All the 3 arrays assignments are valid
    // Array looks like {{1,2,3},{4,5,6}}

并非强制要求每个内部元素的大小相同。

int [][] intArray = new int[2][];
    intArray[0] = {1,2,3};
    intArray[1] = {4,5};
    //array looks like {{1,2,3},{4,5}}

    int[][] intArray = new int[][2] ; // This won't compile. Keep this in mind.

如果使用上述语法,则必须确保前进方向必须在方括号中指定值。否则就无法编译。一些例子:

int [][][] intArray = new int[1][][];
    int [][][] intArray = new int[1][2][];
    int [][][] intArray = new int[1][2][3];

另一个重要特征是协变的

Number[] numArray = {1,2,3,4};   // java.lang.Number
    numArray[0] = new Float(1.5f);   // java.lang.Float
    numArray[1] = new Integer(1);    // java.lang.Integer
   // You can store a subclass object in an array that is declared
   // to be of the type of its superclass.
   // Here 'Number' is the superclass for both Float and Integer.

   Number num[] = new Float[5]; // This is also valid

重要提示:对于引用的类型,数组中存储的默认值为null。

uqjltbpv

uqjltbpv11#

声明和初始化arraylist的另一种方法:

private List<String> list = new ArrayList<String>(){{
    add("e1");
    add("e2");
}};
wbrvyc0a

wbrvyc0a12#

如果你说的“数组”是指 java.util.Arrays ,您可以这样做:

List<String> number = Arrays.asList("1", "2", "3");

Out: ["1", "2", "3"]

这个很简单,很直接。

vatpfxk5

vatpfxk513#

为Java8及更高版本声明和初始化。创建一个简单的整数数组:

int [] a1 = IntStream.range(1, 20).toArray();
System.out.println(Arrays.toString(a1));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

为[-50,50]和双精度[0,1e17]之间的整数创建一个随机数组:

int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();

二序功率:

double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray();
System.out.println(Arrays.toString(a4));
// Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]

对于字符串[],必须指定构造函数:

String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));

多维数组:

String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
    .toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]
xzv2uavs

xzv2uavs14#

对于创建类对象数组,可以使用 java.util.ArrayList . 要定义数组,请执行以下操作:

public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();

为数组赋值:

arrayName.add(new ClassName(class parameters go here);

从数组读取:

ClassName variableName = arrayName.get(index);

注: variableName 是对数组的引用,表示 variableName 将操纵 arrayName 对于循环:

//repeats for every value in the array
for (ClassName variableName : arrayName){
}
//Note that using this for loop prevents you from editing arrayName

允许您编辑的for循环 arrayName (常规for循环):

for (int i = 0; i < arrayName.size(); i++){
    //manipulate array here
}
uqxowvwt

uqxowvwt15#

可以使用数组声明或数组文字(但仅当您立即声明并影响变量时,数组文字不能用于重新分配数组)。
对于基本类型:

int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};

// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html

int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort

比如说班级 String ,是一样的:

String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};

第三种初始化方法在以下情况下很有用:先声明数组,然后对其进行初始化,将数组作为函数参数传递,或返回数组。需要显式类型。

String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};

相关问题