如何在 Groovy 中将元素添加到列表中?

编程入门 行业动态 更新时间:2024-10-25 05:24:29
本文介绍了如何在 Groovy 中将元素添加到列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一个清单,就像这样...

Let's say I've got a list, like this...

def myList = ["first", 2, "third", 4.0];

如何在元素的末尾添加(推送)一个元素?我来自 PHP 背景,在那里我会做一些类似 $myList[] = "fifth"; 的事情.Groovy 中的等价物是什么?

How do I add (push) an element to the end of it? I come from a PHP background, and there I would just do something like $myList[] = "fifth";. What's the equivalent of that in Groovy?

推荐答案

来自 文档:

我们可以通过多种方式添加到列表中:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6] assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6] //equivalent method for + def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6] assert [1, *[222, 333], 456] == [1, 222, 333, 456] assert [ *[1,2,3] ] == [1,2,3] assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9] def list= [1,2] list.add(3) //alternative method name list.addAll([5,4]) //alternative method name assert list == [1,2,3,5,4] list= [1,2] list.add(1,3) //add 3 just before index 1 assert list == [1,3,2] list.addAll(2,[5,4]) //add [5,4] just before index 2 assert list == [1,3,5,4,2] list = ['a', 'b', 'z', 'e', 'u', 'v', 'g'] list[8] = 'x' assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

你也可以这样做:

def myNewList = myList << "fifth"

更多推荐

如何在 Groovy 中将元素添加到列表中?

本文发布于:2023-11-22 19:12:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618661.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   元素   如何在   列表中   Groovy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!