如何使用ListBuffer获取列表的元素 [英] How can I get the elements of list using ListBuffer

查看:66
本文介绍了如何使用ListBuffer获取列表的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取列表元素时,我面临一个非常奇怪的问题

I am facing a very weird problem while getting elements of a list

下面是我将参数传递为"bc"和"mn"的代码段

Below is the piece of code where I am passing arguments as "bc" and "mn"

val list1 = List("abc", "def", "mnp")
    val list2 = List(args(0), args(1))
    val header1=list1.filter(x => list2.exists(y => x.contains(y)))
    println(header1)

Output-List("abc","mnp")

Output-List("abc","mnp")

我正在尝试通过不同的方式(通过传递相同的参数)来做到这一点,但是却得到一个空的列表

I am trying to do it in a different way (by passing the same arguments)but getting an empty List

val list1 = List("abc", "def", "mnp")
    //val list2 = List(args(0), args(1))
    val ipList1= new ListBuffer[Any]
    for(i <- 0 to 1){
      ipList1 +=args(i)
    }
    val list2=ipList1.toList
    println(list2)
    val header1=list1.filter(x => list2.exists(y => x.contains(y)))
    println(header1)

Output-List(bc,mn)

Output-List(bc, mn)

List()->这是我得到的空列表

List()-->This is the empty List I am getting

有人可以告诉我我做错了什么地方以及如何做对吗?

Can Someone please tell where I am doing it wrong and How to make it right?

推荐答案

问题是x.contains(y)并不意味着您认为的含义. String具有contains方法,该方法检查另一个String是否是该String的子字符串.但是在您的代码中,y的类型不是String,而是Any.因此,不会调用Stringcontains方法.这是

The problem is that x.contains(y) does not mean what you think it means. String has a contains method that checks whether another String is a substring of this String. But in your code y doesn't have type String, but type Any. So the contains method of String isn't called. It's the contains method of WrappedString which treats the String x as though it's a Seq[Char]. That method doesn't check whether any substring is equal to y but whether any character is equal to y.

显然,解决方案是使用ListBuffer[String].

The solution, obviously, is to use a ListBuffer[String].

这篇关于如何使用ListBuffer获取列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆