Different behavior when declaration type is different(Set vs TreeSet)

前端 未结 4 1044
囚心锁ツ
囚心锁ツ 2021-01-21 05:15
    var set = TreeSet(5,4,3,2,1)
    println(set)

    val diffSet: TreeSet[Int] = set
    // if I change above code to val diffSet: Set[Int] = set
    // the result is          


        
4条回答
  •  悲哀的现实
    2021-01-21 05:30

    Set does not guarantee ordering. Even if the underlying class is a TreeSet, if the expected result is a Set you'll loose the ordering in the first transformation you do.

    If you want ordering, do not use Set. I suggest, say, SortedSet.

提交回复
热议问题