zoukankan      html  css  js  c++  java
  • scala中:: , +:, :+, :::, +++的区别

    初学scala的人都会被Seq的各种操作符所迷惑。下面简单列举一下各个Seq操作符的区别。

    4种操作符的区别和联系

    :: 该方法被称为cons,意为构造,向队列的头部追加数据,创造新的列表。用法为x::list,其中x为加入到头部的元素,无论x是列表与否,它都只将成为新生成列表的第一个元素,也就是说新生成的列表长度为list的长度+1(btw, x::list等价于list.::(x))
    
    scala> var list = List(1,2,3)
    list: List[Int] = List(1, 2, 3)
    
    scala> var list1 = List(4,5,6)
    list1: List[Int] = List(4, 5, 6)
    
    scala> list1 :: list
    res0: List[Any] = List(List(4, 5, 6), 1, 2, 3)
    
    scala> 2 :: list
    res1: List[Int] = List(2, 1, 2, 3)
    
    scala> list.::(5)
    res2: List[Int] = List(5, 1, 2, 3)
    
    :+和+: 两者的区别在于:+方法用于在尾部追加元素,+:方法用于在头部追加元素,和::很类似,但是::可以用于pattern match ,而+:则不行. 关于+:和:+,只要记住冒号永远靠近集合类型就OK了,加号位置决定元素(无论元素还是集合)加在前还是后。
    
    scala> array :+ 6
    res5: Array[Int] = Array(1, 2, 3, 6)
    
    scala> array +: 6  // :需要靠近集合类型
    <console>:13: error: value +: is not a member of Int
           array +: 6
                 ^
    scala> 6 +: array
    res7: Array[Int] = Array(6, 1, 2, 3)
    
    scala> var array1 = Array(4,5,6)
    array1: Array[Int] = Array(4, 5, 6)
    
    scala> array1 +: array
    res8: Array[Any] = Array(Array(4, 5, 6), 1, 2, 3) // 加入集合也只被当做是原集合的一个元素
    
    ++ 该方法用于连接两个集合(列表,数组等),list1++list2
    
    scala> array1 ++ array
    res9: Array[Int] = Array(4, 5, 6, 1, 2, 3)
    
    scala> array ++ array1
    res10: Array[Int] = Array(1, 2, 3, 4, 5, 6)
    
    scala> list1 ++ list
    res11: List[Int] = List(4, 5, 6, 1, 2, 3)
    
    
    ::: 该方法只能用于连接两个List类型的集合
    
    scala> list ::: list1
    res13: List[Int] = List(1, 2, 3, 4, 5, 6)
    
    scala> array ::: array1
    <console>:14: error: value ::: is not a member of Array[Int]
           array ::: array1
    
  • 相关阅读:
    Difference Between Arraylist And Vector : Core Java Interview Collection Question
    Man's Best Friend: The Science Behind the Dog and Human Relationship
    我在微软那些事--微软面试
    北美PM活着的攻略
    C#图解教程 第二十一章 命名空间和程序集
    C#图解教程 第二十章 异步编程
    C#图解教程 第十九章 LINQ
    C#图解教程 第十八章 枚举器和迭代器
    C#图解教程 第十七章 泛型
    C#图解教程 第十六章 转换
  • 原文地址:https://www.cnblogs.com/ios1988/p/7477487.html
Copyright © 2011-2022 走看看