關(guān)于Java數(shù)組聲明、創(chuàng)建、初始化的相關(guān)介紹
本文講述了Java數(shù)組的幾個相關(guān)的方面,講述了對Java數(shù)組的聲明、創(chuàng)建和初始化,并給出其對應(yīng)的代碼。
一維數(shù)組的聲明方式:type var[]; 或type[] var;
聲明數(shù)組時不能指定其長度(數(shù)組中元素的個數(shù)),
Java中使用關(guān)鍵字new創(chuàng)建數(shù)組對象,格式為:數(shù)組名 = new 數(shù)組元素的類型 [數(shù)組元素的個數(shù)]
實(shí)例:TestNew.java:
程序代碼:
public class TestNew
{
public static void main(String args[]) {
int[] s ;
int i ;
s = new int[5] ;
for(i = 0 ; i < 5 ; i++) {
s[i] = i ;
}
for(i = 4 ; i >= 0 ; i--) {
System.out.println("" + s[i]) ;
}
}
}
初始化:
1.動態(tài)初始化:數(shù)組定義與為數(shù)組分配空間和賦值的操作分開進(jìn)行;
2.靜態(tài)初始化:在定義數(shù)字的同時就為數(shù)組元素分配空間并賦值;
3.默認(rèn)初始化:數(shù)組是引用類型,它的元素相當(dāng)于類的成員變量,因此數(shù)組分配空間后,每個元素也被按照成員變量的規(guī)則被隱士初始化。
實(shí)例:
TestD.java(動態(tài)):
程序代碼:
public class TestD
{
public static void main(String args[]) {
int a[] ;
a = new int[3] ;
a[0] = 0 ;
a[1] = 1 ;
a[2] = 2 ;
Date days[] ;
days = new Date[3] ;
days[0] = new Date(2008,4,5) ;
days[1] = new Date(2008,2,31) ;
days[2] = new Date(2008,4,4) ;
}
}
class Date
{
int year,month,day ;
Date(int year ,int month ,int day) {
this.year = year ;
this.month = month ;
this.day = day ;
}
}
TestS.java(靜態(tài)):
程序代碼:
public class TestS
{
public static void main(String args[]) {
int a[] = {0,1,2} ;
Time times [] = {new Time(19,42,42),new Time(1,23,54),new Time(5,3,2)} ;
}
}
class Time
{
int hour,min,sec ;
Time(int hour ,int min ,int sec) {
this.hour = hour ;
this.min = min ;
this.sec = sec ;
}
}
TestDefault.java(默認(rèn)):
程序代碼:
public class TestDefault
{
public static void main(String args[]) {
int a [] = new int [5] ;
System.out.println("" + a[3]) ;
}
}
以上就是關(guān)于Java數(shù)組聲明、創(chuàng)建、初始化的實(shí)例講解,希望大家能夠理解,對大家的學(xué)習(xí)有所幫助。
相關(guān)文章
java實(shí)現(xiàn)省市區(qū)三級聯(lián)動
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)省市區(qū)三級聯(lián)動,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-06-06
Java按時間梯度實(shí)現(xiàn)異步回調(diào)接口的方法
這篇文章主要介紹了Java按時間梯度實(shí)現(xiàn)異步回調(diào)接口,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08
基于springboot activiti 配置項(xiàng)解析
這篇文章主要介紹了springboot activiti 配置項(xiàng)解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09

