📅  最后修改于: 2020-03-28 03:45:02             🧑  作者: Mango
先决条件:Java中的数组
使用数组时,我们必须执行3个任务,即声明,创建,初始化或赋值。
数组声明:
int[] arr;
创建数组:
// 数组size = 3
int[] arr = new int[3];
数组初始化:
arr[0] = 1;
arr[1] = 2;
arr[3] = 3;
int intArray[]; // 声明
intArray = new int[20]; // 分配内存
将元素分配给数组时的一些重要事实:
// Java元素分配给数组
public class Test {
public static void main(String[] args)
{
int[] arr = new int[3];
arr[0] = 1;
arr[1] = 'a';
byte b = 10;
arr[2] = b;
System.out.println(arr[0] + arr[1] + arr[2]);
}
}
输出:
108
// Java元素分配给数组
public class Test {
public static void main(String[] args)
{
int[] arr = new int[3];
// 把long分配给int.
arr[0] = 10l;
arr[1] = 'a';
byte b = 10;
arr[2] = b;
System.out.println(arr[0] + arr[1] + arr[2]);
}
}
输出:
possible loss of precision.
// Java元素分配给数组
public class Test {
public static void main(String[] args)
{
char[][] arr = new char[2][2];
// 把long分配给int.
arr[0][0] = 10l;
arr[0][1] = 'a';
char b = 10;
arr[1][0] = b;
// 把double分配给char
arr[1][1] = 10.6;
}
}
输出:
error: incompatible types: possible lossy conversion from long to char
error: incompatible types: possible lossy conversion from double to char
// Java展示 Number类型array
public class Test {
public static void main(String[] args)
{
Number[] num = new Number[2];
num[0] = new Integer(10);
num[1] = new Double(20.5);
System.out.println(num[0]);
System.out.println(num[1]);
}
}
输出:
10
20.5
// Java展示 Number类型array
public class Test {
public static void main(String[] args)
{
Number[] num = new Number[3];
num[0] = new Integer(10);
num[1] = new Double(20.5);
// String不是Number类的子类.
num[2] = new String(“GFG");
}
}
输出:
Compile-time error(incompatible types) 编译错误
// Java展示 Number类型array
public class Test {
public static void main(String[] args)
{
Number[][] arr = new Number[2][2];
arr[0][0] = 10l;
// 把char分配给Number类array
arr[0][1] = 'a';
byte b = 10;
arr[1][0] = b;
// 把String分配给Number类array
arr[1][1] = "GEEKS";
}
}
输出:
error: incompatible types: char cannot be converted to Number
error: incompatible types: String cannot be converted to Number
// Java展示接口Interface类型array
public class Test {
public static void main(String[] args)
{
Runnable[] run = new Runnable[2];
// Thread类实现类Runnable接口.
run[0] = new Thread();
run[1] = new Thread();
}
}
// Java展示接口Interface类型array
public class Test {
public static void main(String[] args)
{
Runnable[] run = new Runnable[2];
run[0] = new Thread();
// String类没有实现Runnable接口.
run[1] = new String(“GFG");
}
}
输出:
Compile-time error(Incompatible types)
说明:在上面的程序中,我们给出了导致编译时错误的String类的元素。因为我们知道String不实现Runnable接口。