Groovy列表

本文通过多个示例展示了如何使用Groovy进行数组的基本操作,包括追加元素、检查元素是否存在、获取元素、判断数组是否为空、从数组中删除元素等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

末尾追加
size()数组长度

class Example { 
   static void main(String[] args) { 
     def list1 = [] ;
    def list2 = [1,2,3,4];  
    list2.add(12);
    list2.add(12); 
    println(list2.size());
    println(list2);
   } 
}

6
[1, 2, 3, 4, 12, 12]

contains 包含元素返回为true

class Test{
	static void main(String[] args){
		def list2 = [1,2,3,4]; 
		println(list2.contains(1));
	}
}

返回值是true

get (int number)获取元素的位置

class Test {
	static void main(String [] args){
		String a = [1,2,3];
		println(get(1));
	}
}

打印值是2,获取索引值为1的value

isEmpty是否为空

class Example { 
   static void main(String[] args) { 
      def lst = [11, 12, 13, 14]; 
      def emptylst = [];
		
      println(lst.isEmpty()); 
      println(emptylst.isEmpty()); 
   } 
}

false
true

minus数组中删除数组,删除不存在的不会报错

class Test{
	static void main(String[]args){
		def list1 = [1,3,4,45,9];
		deef list2 = 1list.minus([1,3,4,2]);
		println(list2 );
	}
}

[45, 9]

plus function which is used to add a new array to the existing array.

class Test{
	static void main(String []args){
		def list1 = [1,2,3,5];
		def list2 = list1.plus([4,6]);
		println(list1);
		println(list2);
		println(list2.sort());
	}
}

[1, 2, 3, 5]
[1, 2, 3, 5, 4, 6]
[1, 2, 3, 4, 5, 6]

pop删除最后 一个元素

class Test{
	static void main(String []args){
		def list1 = [1,2,3,5];
		def value= list1.pop();//返回删除的值
		println(list1);//
		println(value);
	}
}

[1,2,3]
5
remove删除指定索引的值

class Test{
	static void main(String [] args){
		def ar = [1,3,4,5];
		def v = ar.remove(1);//返回删除的值
		println(ar);
		println(ar.reverse());
		println(v);
	}
}

[1, 4, 5]
[5, 4, 1]
3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值