如何在Java中声明和初始化数组?
如何在Java中声明和初始化数组?您可以使用数组声明或数组文字(但只有当您立即声明并影响变量时,数组文字才能用于重新分配数组) 对于基本类型:如何在Java中声明和初始化数组?,java,arrays,Java,Arrays,如何在Java中声明和初始化数组?您可以使用数组声明或数组文字(但只有当您立即声明并影响变量时,数组文字才能用于重新分配数组) 对于基本类型: 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/
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"};
或者
// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];
它声明了一个名为
arrayName
的数组,大小为10(可以使用元素0到9)。可以通过多种方式在Java中声明数组:
float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};
您可以在网站和中找到更多信息
也是有效的,但我更喜欢类型后面的括号,因为更容易看出变量的类型实际上是一个数组。如果您了解每个部分,我觉得这很有帮助:
Type[] name = new Type[5];
Type[]
是名为name的变量的类型(“name”称为标识符)。文字“Type”是基类型,括号表示这是该基的数组类型。数组类型是它们自己的类型,这允许您创建多维数组,如Type[][
(Type[]的数组类型)。关键字new
表示为新数组分配内存。括号之间的数字表示新阵列的大小以及要分配的内存量。例如,如果Java知道基本类型type
需要32个字节,并且您想要一个大小为5的数组,那么它需要在内部分配32*5=160个字节
您还可以使用已经存在的值创建数组,例如
int[] name = {1, 2, 3, 4, 5};
这不仅会创建空空间,还会用这些值填充它。Java可以判断原语是整数,并且有5个,因此可以隐式地确定数组的大小。此外,如果您需要更动态的内容,还可以使用列表接口。这样做效果不好,但更灵活:
List<String> listOfString = new ArrayList<String>();
listOfString.add("foo");
listOfString.add("bar");
String value = listOfString.get(0);
assertEquals( value, "foo" );
List listOfString=new ArrayList();
添加(“foo”);
添加(“条”);
字符串值=listOfString.get(0);
资产质量(价值,“foo”);
以下显示了数组的声明,但数组未初始化:
int[] myIntArray = new int[3];
下面显示了数组的声明和初始化:
int[] myIntArray = {1,2,3};
int[] myIntArray = new int[]{1,2,3};
arrayName.add(new ClassName(class parameters go here);
ClassName variableName = arrayName.get(index);
现在,下面还显示了数组的声明和初始化:
int[] myIntArray = {1,2,3};
int[] myIntArray = new int[]{1,2,3};
arrayName.add(new ClassName(class parameters go here);
ClassName variableName = arrayName.get(index);
但是第三个显示了匿名数组对象创建的属性,它是由一个引用变量“myIntArray”指向的,所以如果我们只写“newint[]{1,2,3}”;那么这就是匿名数组对象的创建方式
如果我们只写:
int[] myIntArray;
这不是数组的声明,但以下语句使上述声明完成:
myIntArray=new int[3];
有两种类型的数组。
一维阵列 默认值的语法:
int[] num = new int[5];
或(不太受欢迎)
给定值的语法(变量/字段初始化):
或(不太受欢迎)
注意:为了方便起见,int[]num更可取,因为它清楚地表明您在这里谈论的是数组。否则没有区别。不客气。多维数组 宣言 或 或 初始化 或 不规则阵列(或非矩形阵列) 因此,我们在这里明确定义列。
另一种方式: 访问: 不规则数组是多维数组。
有关说明,请参见位于的多维数组详细信息。如果要使用反射创建数组,可以执行以下操作:
int size = 3;
int[] intArray = (int[]) Array.newInstance(int.class, size );
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
以基本类型
int
为例。有几种方法可以声明和int
数组:
int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
在所有这些中,您可以使用int i[]
而不是int[]i
通过反射,您可以使用(Type[])Array.newInstance(Type.class,capacity)代码>
请注意,在方法参数中,..
表示变量参数
。基本上,任何数量的参数都可以。使用代码更容易解释:
public static void varargs(int fixed1, String fixed2, int... varargs) {...}
...
varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
在方法内部,varargs
被视为正常的int[]
<代码>类型…
只能在方法参数中使用,因此int。。。i=newint[]{}
将不会编译
请注意,将int[]
传递给方法(或任何其他Type[]
)时,不能使用第三种方法。在语句int[]i=*{a,b,c,d等}
中,编译器假定{…}
表示int[]
。但这是因为您正在声明一个变量。将数组传递给方法时,声明必须是new-Type[capacity]
或new-Type[]{…}
多维数组
多维数组更难处理。从本质上讲,二维数组是数组的数组int[][]
表示int[]
s的数组。关键是如果一个int[][]
被声明为int[x][y]
,最大索引是i[x-1][y-1]
。基本上,矩形int[3][5]
是:
[0, 0] [1, 0] [2, 0]
[0, 1] [1, 1] [2, 1]
[0, 2] [1, 2] [2, 2]
[0, 3] [1, 3] [2, 3]
[0, 4] [1, 4] [2, 4]
声明对象引用数组:
class Animal {}
class Horse extends Animal {
public static void main(String[] args) {
/*
* Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
*/
Animal[] a1 = new Animal[10];
a1[0] = new Animal();
a1[1] = new Horse();
/*
* Array of Animal can hold Animal and Horse and all subtype of Horse
*/
Animal[] a2 = new Horse[10];
a2[0] = new Animal();
a2[1] = new Horse();
/*
* Array of Horse can hold only Horse and its subtype (if any) and not
allowed supertype of Horse nor other subtype of Animal.
*/
Horse[] h1 = new Horse[10];
h1[0] = new Animal(); // Not allowed
h1[1] = new Horse();
/*
* This can not be declared.
*/
Horse[] h2 = new Animal[10]; // Not allowed
}
}
数组是项的顺序列表
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
以使用新类型(..)
初始化它们,像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) };
Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
// ^ ^ array reference
// ^ actual data
通常,您可以创建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
,因为每个数组都有一个引用
class Animal {}
class Horse extends Animal {
public static void main(String[] args) {
/*
* Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
*/
Animal[] a1 = new Animal[10];
a1[0] = new Animal();
a1[1] = new Horse();
/*
* Array of Animal can hold Animal and Horse and all subtype of Horse
*/
Animal[] a2 = new Horse[10];
a2[0] = new Animal();
a2[1] = new Horse();
/*
* Array of Horse can hold only Horse and its subtype (if any) and not
allowed supertype of Horse nor other subtype of Animal.
*/
Horse[] h1 = new Horse[10];
h1[0] = new Animal(); // Not allowed
h1[1] = new Horse();
/*
* This can not be declared.
*/
Horse[] h2 = new Animal[10]; // Not allowed
}
}
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() }
};
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) };
int [][]..[] array =
// ^ M times [] brackets
{{..{
// ^ M times { bracket
// this is array[0][0]..[0]
// ^ M times [0]
}}..}
// ^ M times } bracket
;
Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
// ^ ^ array reference
// ^ actual data
int[] array = new int[n]; // "n" being the number of spaces to allocate in the array
int[] array = {1,2,3,4 ...};
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();
arrayName.add(new ClassName(class parameters go here);
ClassName variableName = arrayName.get(index);
//repeats for every value in the array
for (ClassName variableName : arrayName){
}
//Note that using this for loop prevents you from editing arrayName
for (int i = 0; i < arrayName.size(); i++){
//manipulate array here
}
private List<String> list = new ArrayList<String>(){{
add("e1");
add("e2");
}};
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]
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]]
int[] a = IntStream.iterate(10, x -> x <= 100, x -> x + 10).toArray();
Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray();
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var letters = new String[]{"A", "B", "C"};
String[] strs = IntStream.range(0, 15) // 15 is the size
.mapToObj(i -> Integer.toString(i))
.toArray(String[]::new);
var values = new int[] { 1, 2, 3 };
int[] values = { 1, 2, 3 }
List<String> number = Arrays.asList("1", "2", "3");
Out: ["1", "2", "3"]
int intArray[] = new int[3];
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};
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
int[] a = new int[5];
int[] a = {1, 2, 3, 4, 5};
datatype[] arrayname = new datatype[requiredarraysize];
String[] a = {"as", "asd", "ssd"};
char[] a = {'a', 's', 'w'};
double[] a = {1.2, 1.3, 12.3};
type var-name[];
OR
type[] var-name;
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]);
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};
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);
}
}
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));
}
}