【问题标题】:Convert Mutable list to a custom List of object将可变列表转换为自定义对象列表
【发布时间】:2023-02-21 23:45:39
【问题描述】:

我正在尝试将可变列表转换为自定义对象列表以存储纬度和经度。

但是,我不确定转换是否正确

所以 Mutable List 被声明为 val coordinateArray: MutableList<MutableList<Double>> = mutableListOf()

这就是我转换它的方式

    val pointList: MutableList<Point> = ArrayList()
    for (i in coordinateArray.indices) {
        val point = Point(i.toDouble(), (i+1).toDouble())
        pointList.add(point)
    }

    val distance = 0.0001
    val bufferedPolygonList: List<Point> = AreaBuffer.buffer(pointList, distance)

上面的代码生成一个缓冲多边形坐标列表。

在测试上面的坐标时,坐标是无穷大,这是不正确的。

如果我做错了什么,你能告诉我吗?

【问题讨论】:

    标签: kotlin coordinates


    【解决方案1】:

    我认为您的解决方案的问题在于您正在插入迭代的值,而不是将它们用作索引以从 coordinateArray 列表中获取值。

    这是它的实现

    public val Collection<*>.indices: IntRange
        get() = 0..size - 1
    

    尝试使用类似上面的代码

    val coordinateArray: MutableList<MutableList<Double>> = mutableListOf(
        mutableListOf(1.0, 2.0),
        mutableListOf(2.0, 3.0),
        mutableListOf(3.0, 4.0)
    )
    val pointList: MutableList<Point> = ArrayList()
    for (i in coordinateArray.indices) {
        val point = Point(coordinateArray[i][0], coordinateArray[i][1])
        pointList.add(point)
    }
    

    另外,请注意,最好使用不可变结构,您还可以使用 map 函数简化代码

    val coordinateArray: List<List<Double>> = listOf(
        listOf(1.0, 2.0),
        listOf(2.0, 3.0)
    )
    val pointList = coordinateArray.map { Point(it[0], it[1]) }
    println(pointList)
    

    【讨论】:

      【解决方案2】:

      您正在转换 Int指数加倍而完全忽略实际内容来自coordinateArray。您需要使用索引检索这些值。

      val pointList: MutableList<Point> = ArrayList()
      for (i in coordinateArray.indices) {
          val point = Point(coordinateArray[i][0], coordinateArray[i][1])
          pointList.add(point)
      }
      

      这里有一些更简洁的方法:

      val pointList = buildList<Point> {
          for (i in coordinateArray.indices) {
              val point = Point(coordinateArray[i][0], coordinateArray[i][1])
              add(point)
          }
      }
      
      val pointList = coordinateArray.map { Point(it[0], it[1]) }
      

      【讨论】:

      • 我上面的所有代码都假定偶数大小为 coordinateArray。
      • 实际上,我只是注意到您的输入是一个二维列表,所以偶数大小无关紧要。我修复了上面的代码来解决这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      相关资源
      最近更新 更多