Groovy笔记(3)_集合
集合概述 ? 1、集合应用很广泛 2、Groovy直接在语言内使用集合
3、每个Groovy集合都是java.util.Colleciton或java.util.Map的实例 4、List,String,StringBuffer,Range,Map,File,Matcher都是用同一的size()方法获取长度. 如:StringBUffer x = new StringBuffer('ssss'); ??????print x.size() //输出4 ? ? 列表List一 ? def toys =[['a','001'],[2,'002'],['c','003']]
列表List二 ? 1、toys<<[4,'004'] //追加元素 ???? println toys[-1] //输出:[4,'004'] ? 2、toys1 = [1,2,3] //连接链表 ???? toys2 = toys1 + [4,5] ???? println toys2? // 输出:[1,3,4,5] ? 3、toys3 = toys2 - [5]//列表中删除元素 ???? println toys3 //输出:[1,4] ? 列表List三 ? def toy6 =[]
列表List的方法一 ? 1、def list=[1,4]
? 列表List的方法二 ? 1、有些方法会修改原列表,有些方法不修改原列表而只是产生新的列表。 ???? def fList =[1,3[4,5]]
2、计算元素 ???? def gList = [1,1,3] ?????println gList.count(3)????????????????????? //输出:2?? 有两个3 ? ? 映射Map一 ? 1、def bookMap = [:] //定义空map ???? println bookMap.getClass() // 输出class java.util.LinkedHashMap ???? assert bookMap.size() == 0 ? 2、def toyMap = [1:'toy1',2:'toy2'] ???? assert toyMap.containsValue('toy1') ???? assert toyMap.containsKey(1) ? ? 映射Map二 ? 1、println toyMap??????????????????????? //输出整个map,[1:'toy1',2:'toy2'] ???? println toyMap[2]?????????????????? // toy2 ???? println toyMap.get(1)???????????? // toy1 ? 2、toyMap.each{toy -> println toy.key + ':' + toy.value} // 1:toy1 2:toy2(换行输出) ,toy是指定的闭包参数 ???? toyMao.each{println it.key + ':' + it.value}???????????????? //输出同上,it是默认闭包参数 ? ? 映射MAP三 ?
? 范围一 ? 1、def aRange?= 1..<5 ???? println aRange??????????????? //输出[1,4] ???? println aRange.class????????//class groovy.lange.IntRange ???? assert aRange instanceof List ????? (1..<5)范围是IntRange的对象,是特殊的List ? ? 范围二 ? 1、def bRange = 'a'..<'e' ???? println bRange???? // 输出: ["a","b","c","d"] ???? println bRange.class?? //输出groovy.lang.ObjectRange ???? assert bRange instanceof List ? ('a'..<'e')是 ObjectRange的对象,是特殊的List ? ? 范围三 ? 倒序 1、def cRange = 5..1 ???? println cRange???????????????????????//[5,1] 2、def dRange?=?'e'..'a'????????????? //["e","d","b"] ? ? 范围Range的方法 ? def eRange =1..10
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |