Groovy中,如何根据元素本身而不是下标删除集合元素呢

我知道Groovy是动态语言,它有多方法的机制,在Collection中remove有remove(int index)remove(Object o)两个版本,很自然,我就想到,如果我集合中元素本身就是整型,那么假定我要删除集合中的值为5的元素,它该如何选择呢?
考虑下面代码:

Collection<Integer> collection=new ArrayList<>();
collection.add(5);
collection.add(6);
collection.remove(5)
collection.forEach({
    println "$it"
})

这个集合的元素是Integer类型,我往里面添加了两个元素,分别是5和6。现在,我想要将“5”这个元素移除,即只保留“6”。但是根据输出结果来看,Groovy果然将其是做了下标,从而抛出越界异常:

Caught: java.lang.IndexOutOfBoundsException: Index: 5, Size: 2

我用下面几种手段,同样得到越界异常:

collection.remove(new Integer(5))
collection.remove(Integer.valueOf(5))
collection.remove(5 as Integer)
Integer ele=5;
collection.remove(ele)

……
所以我想知道,在这种情况下如何解决呢?

阅读 3.8k
1 个回答
Collection<Integer> collection=new ArrayList<>();
collection.add(5);
collection.add(6);
collection.remove(5); // 这里越界了 只能删除 0和1

在Collection中remove有remove(int index)remove(Object o)你不都写明白了了吗
有两种删除方式 第一种 集合下标 第二种 元素引用

你一个集合 加入两个元素 肯定是下标 0 和 1 你使用了下标方式,却要删除 5 也就是第六个元素
肯定crash的

你想查找?然后删除?

        Collection<Integer> collection=new ArrayList<>();
        collection.add(5);
        collection.add(6);
        collection.add(100);
        collection.add(300);

        // 删除100
        int index = -1;
        for(int i = 0;i<collection.size();i++) {
            if(collection[i]==100){
                index = i;
                break;
            }
        }

        if(index>0) {
            collection.remove(index);
        }
        print(collection);

我哪会写Groovy呀 大搞这个意思 应该可以执行。

你说这个效率不高?
你没说你要干什么呀~
首先 你得知道什么是集合。集合和数组有什么区别 不管是集合还是数组 只能遍历查找并且操作的。
其次,你希望高效查找,那你就要使用hash表,通过hash值当时快速定位然后操作。
这些都是编程基本的东西~

算了 帮人帮到底,你真的不查一下文档吗?查一下函数列表也是好的。

        Collection<Integer> collection=new ArrayList<>();
        collection.add(5);
        collection.add(6);
        collection.remove(collection.indexOf(5));
        print(collection);

你想搞清楚更多 去看看官方文档吧

        int a = 100
        Integer b = 20


        if( Integer == a.class){
            print("hello\n")
        }

        if( b.class == a.class){
            print("hello\n")
        }

你看下这几行代码 你也许能明白一些。这里ab没什么区别,唯一区别就是b可null
我Groovy基本等于0 任何一个编程语言 你都需要去适应
多读文档吧

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进