亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

groovy 定義數組方法?

groovy 定義數組方法?

瀟瀟雨雨 2019-01-29 06:06:12
def AR_Interface=new AUTOSAR_Interface[2];AR_Interface[0]=new AUTOSAR_Interface();AR_Interface[1]=new AUTOSAR_Interface();AUTOSAR_Interface是我自己定義的一個class。我需要先聲明數組AR_Interface,然后再初始化,有沒有簡易的代碼,可以讓這兩步同時完成,謝謝。
查看完整描述

2 回答

?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

一、數組的定義及賦初值
在Groovy語言中,數組的定義和Java語言中一樣。
def a = new String[4]

def nums = newint[10]

def objs = new Object[3]

然后賦值也一樣:
a[0] = 'a'
a[1] = 'b'
a[2] = 'c'
a[3] = 'd'

所不同的在于在數組定義的時候賦初值。
Java語言里,對一個字符串數組這樣定義:
String[] strs = new String[]{'a','b','c','d'};

而在Groovy語言中,對一個字符串數組則需要這樣定義:
def strs = ['a','b','c','d'] as String[]

二、數組的遍歷
在Groovy語言中,對數組的遍歷方法很多,常用的是使用each方法:
a.each{

println it
}

當然,你也可以使用增強for循環
for(it in a)
{
println it
}

你還可以使用如下的遍歷方式:
(0..<a.length).each{
println a[it]
}

三、數組和List之間的轉化
List對象轉化成數組對象非常簡單:
List list = ['a','b','c','d']

def strs = list as String[]

println strs[0]

絕對沒有Java語言那么復雜:
List list = new ArrayList();
list.add("1");
String[] strs = (String[])list.toArray(new String[0]);

System.out.println(strs[0]);

而從數組轉化成List對象也非常簡單:
def strs = ['a','b','c','d'] as String[]

List list = strs.toList()

println list.get(0)

你也可以這樣轉化:
def strs = ['a','b','c','d'] as String[]
List list = strs as List

println list.get(0)

而在Java語言中,你需要這樣轉化:

List list = Arrays.asList(strs)



查看完整回答
反對 回復 2019-03-15
?
慕娘9325324

TA貢獻1783條經驗 獲得超4個贊

def AR_Interface=new AUTOSAR_Interface[2]{new AUTOSAR_Interface(),new AUTOSAR_Interface()};

查看完整回答
反對 回復 2019-03-15
  • 2 回答
  • 0 關注
  • 2747 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號