TreeSet 및 맵 함수에 관한 다음과 같은 동작을 설명하고 이해하는 방법을 모르겠습니다.TreeSet 매핑 후 순서를 준수하지 않습니다
나는 수수께끼의 조각을 놓치고 있다고 생각합니다. 그 문제에 대한 어떤 빛이라도 매우 환영받을 것입니다.
scala> class Person(val name: String, val age: Int) extends Ordered[Person]{
| def compare(that: Person) = {
| val nameComparison = name.compareToIgnoreCase(that.name)
| if(nameComparison != 0){
| nameComparison
| }else{
| age.compareTo(that.age)
| }
| }
| override def toString = s"$name || $age"
| }
defined class Person
scala> import scala.collection.immutable.TreeSet
import scala.collection.immutable.TreeSet
scala> val tsPersons = TreeSet(
| new Person("Vivi", 31),
| new Person("ViVi", 4),
| new Person("vivi", 14)
|)//1) printed in expected order
tsPersons: scala.collection.immutable.TreeSet[Person] = TreeSet(ViVi || 4, vivi || 14, Vivi || 31)
scala> tsPersons.map(p => p) //2) printed in expected order
res0: scala.collection.immutable.SortedSet[Person] = TreeSet(ViVi || 4, vivi || 14, Vivi || 31)
scala> tsPersons.map(p => (p.name, p.age)) //3) order messed up
res1: scala.collection.immutable.SortedSet[(String, Int)] = TreeSet((ViVi,4), (Vivi,31), (vivi,14))
scala> tsPersons.toList.map(p => (p.name, p.age)) //4) printed in expected order
res2: List[(String, Int)] = List((ViVi,4), (vivi,14), (Vivi,31))
인쇄 중 "1)"에서 tsPerson이 올바르게 정렬 된 것을 볼 수 있습니다.
"2)"및 "3)"에서지도 메서드의 요소 순서가 일관되지 않습니다.
마지막으로 toList 메소드로 "4)"를 인쇄 할 때 올바르게 정렬 된 List에서 작업 할 수 있으므로 목록의 map 메소드는 이전에 작동하지 않았던 동일한 함수 리터럴 p => (p.name, p.age)
으로 올바르게 작동합니다.
Sorted 또는 TreeSet 또는 map에 대해 잘 모르는 뭔가가있을 것입니다.
미리 도움을 주셔서 감사합니다.
아주 좋은 설명을해야합니다. 모든 것이 이제 분명합니다. 고맙습니다. –