首页 > 解决方案 > 在 Kotlin 中,如何创建类名是变量的类的实例?

问题描述

我正在用 Kotlin 编写一个 Graph 类。到目前为止,这是我的代码:

import java.util.*

class Graph<Class>(connectionProb: Double) {
    // a general network class
    val nodes = mutableListOf<Class>()
    val connectionProb = connectionProb
    val connections = hashMapOf<Class, MutableList<Class>>()

    var nextID = 0

    private fun createNode() {
        // Here is where I need help
    }
}

我希望能够为每个 Graph 指定节点类型。上面的代码将编译,但我不确定如何初始化新节点。无论其类型如何,我想传递给每个节点的唯一参数是nextID.

谢谢!

标签: kotlin

解决方案


您应该做的第一件事是class为您的 定义 a graph node,而不是维护 a mapfor 连接,让每个节点维护其连接列表。所以你code看起来像这样

class Graph<T>(connectionProb: Double) {

var nextId = 0
val nodes = mutableListOf<Node<T>>()

// Define a node class, so if you have graph of Integer then you want a node of Integer
class Node<T>(var id: Int){
    val connections = mutableListOf<Node<T>>()

    fun addConnection(newConnection: Node<T>){
        connections.add(newConnection)
    }

    override fun toString() = "$id"
    /** add other functions, such as remove etc */
}

fun createNode(){
    var newNode = Node<T>(nextId++)
    nodes.add(newNode)
}

}

现在要使用它graph,您将执行以下操作

fun main(){
    var myGraph = Graph<Integer>(10.9)
    myGraph.createNode()
    myGraph.createNode()
    myGraph.nodes[0].addConnection(myGraph.nodes[1])

    /* Print all nodes in graph */
    for(node in myGraph.nodes) print("  $node")

    /* Print connections of first node */
    for(node in myGraph.nodes[0].connections) print("\n\nConnection id: $node")
}

请注意,这将使您大致了解如何实施图,并且您可以在实施中改进许多事情。要了解更多信息,我建议您阅读一本好书,例如Java 中的数据结构和算法


推荐阅读