Java重载构造函数强制int参数
我在一个类中有两个重载的构造函数方法(来自 UJMP 包):
DefaultSparseIntMatrix(long... size)
并且
DefaultSparseIntMatrix(int maximumNumberOfEntries, long... size)
我想用 int 调用第二个构造函数方法,但是编译器给出了此错误:
reference to DefaultSparseIntMatrix is ambiguous
这就是我现在调用它的方式:
Matrix m = new DefaultSparseIntMatrix((int) (vertices.length*50), (long) vertices.length, (long) vertices.length);
如何强制第一个参数是 int,而不是 long? 我知道相反的方法,只需转换为 (long)
,但我需要它是一个 int 。
I've got two overloaded constructor methods in a class (from UJMP package):
DefaultSparseIntMatrix(long... size)
and
DefaultSparseIntMatrix(int maximumNumberOfEntries, long... size)
I want to call the second one with the int, but the compiler gives this error:
reference to DefaultSparseIntMatrix is ambiguous
This is how I call it right now:
Matrix m = new DefaultSparseIntMatrix((int) (vertices.length*50), (long) vertices.length, (long) vertices.length);
How can I force the first parameter to be an int, and not a long?
I know the other way around, just cast to a (long)
, but I need it to be an int.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试
vararg 是数组的语法糖,它还允许直接传入数组
try
the vararg is syntactic sugar for an array and it also allows passing in an array directly
调用带有 long 列表或 int 后跟 long 列表的函数只是自找麻烦,特别是因为 java 会自动将 int 转换为 long 。 (换句话说,您传递给该构造函数的内容适用于任一构造函数)。
如果您对此参数模式死心塌地(我强烈建议您更改),则您将必须采用 Integer 类型(而不是 int 类型),并显式地将 Integer 对象传递到函数中。
换句话说,试试这个:
和
Calling a function with a list of longs, or an int followed by a list of longs, is just asking for trouble, especially because java will automatically cast an int into a long for you. (In other words, what you have passed into that constructor would work for either one).
If you are dead set on this parameter pattern (which I strongly suggest you change), You are going to have to take in type Integer (as opposed to type int), and explicitly pass in an Integer object into the function.
In otherwords, try this:
and
我将使用构建器模式并使用类似的东西,它与构造函数一样易于使用,并且其目的更清晰:
构建方法调用 DefaultSparseIntMatrix 的私有构造函数,并将构建器本身作为唯一参数,构造函数获取数据来自建筑商。
I would use the builder pattern and use something like this, which is as easy to use as a constructor and clearer in its purpose:
The build method calls a private constructor of DefaultSparseIntMatrix with the builder itself as unique argument, and the constructor gets the data from the builder.