kotlin - 在 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
.
谢谢!
解决方案
您应该做的第一件事是class
为您的 定义 a graph
node
,而不是维护 a map
for 连接,让每个节点维护其连接列表。所以你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 中的数据结构和算法
推荐阅读
- sql - 扫描列以获取值并使用结果选择其他列
- c# - 努力添加到 ListBox
- erlang - 运行 crashdump_viewer 时,“Class FIFinderSyncExtensionHost is implemented in both mean”是什么意思?
- python - 在 Pandas 散点图中设置错误栏样式失败
- python - TensorfFlow 对象检测 API - ModuleNotFoundError:没有名为“object_detection”的模块
- node.js - Deepin 20 和更新的 Nodejs
- r - 改变 Paste0 Min Max 以创建新的 id 变量
- julia - 如何遍历字符串中的行?
- processing - 处理 - 球从屏幕边缘反弹时模糊片刻
- google-apps-script - 如何使用 Google Apps 脚本返回 getVisibleValues()?