gpt4 book ai didi

java - 试图在 Java 中初始化 Scala 创建的类

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:59:35 24 4
gpt4 key购买 nike

我正在尝试学习 Scala,所以我决定用它来实现数据结构。我从 Stack 开始。我创建了以下 Stack 类。

class Stack[A : Manifest]() {

var length:Int = -1
var data = new Array[A](100)

/**
* Returns the size of the Stack.
* @return the size of the stack
*/
def size = {length}

/**
* Returns the top element of the Stack without
* removing it.
* @return Stacks top element (not removed)
*/
def peek[A] = {data(length)}

/**
* Informs the developer if the Stack is empty.
* @return returns true if it is empty else false.
*/
def isEmpty = {if(length==0)true else false}

/**
* Pushes the specified element onto the Stack.
* @param The element to be pushed onto the Stack
*/
def push(i: A){
if(length+1 == data.size) reSize
length+=1
data(length) = i;
}

/**
* Pops the top element off of the Stack.
* @return the pop'd element.
*/
def pop[A] = {
length-=1
data(length)
}

/**
* Increases the size of the Stack by 100 indexes.
*/
private def reSize{
val oldData = data;
data = new Array[A](length+101)
for(i<-0 until length)data(i)=oldData(i)
}
}

然后我尝试使用以下方法在我的 Java 类中初始化这个类

Stack<Integer> stack = new Stack<Integer>();

但是,我被告知构造函数不存在,我应该添加一个参数来匹配 Manifest。为什么会发生这种情况,我该如何解决?

最佳答案

Alexey 给了你正确的解释,但绝对可以在你的代码中创建 list (你只需要一个 java.lang.Class 对象,你可以在 Java 中轻松创建它)。

首先,您应该向 Stack 的伴随对象添加一个 java 友好的工厂方法:

object Stack {
def ofType[T]( klass: java.lang.Class[T] ) = {
val manifest = new Manifest[T] {
def erasure = klass
}
new Stack()(manifest)
}
}

此方法将生成适当的 list (来自 java 类)并将其显式传递给 Stack 构造函数。然后,您可以毫不费力地从 Java 使用它:

Stack<String> stack = Stack.ofType( String.class );
stack.push( "Hello" );
stack.push( "World" );

System.out.println( stack.size() );
System.out.println( stack.peek() );

关于java - 试图在 Java 中初始化 Scala 创建的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9860716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com