[英]Java, how to read multiple data types from one function input?
let's say I want to call a function in my code and I want to input an integer in one case and in another case a string/boolean/char... I know var
is used for doing this but it doesn't work in my code.假设我想在我的代码中调用 function,我想在一种情况下输入 integer,在另一种情况下输入字符串/布尔值/字符...我知道var
用于执行此操作,但它在我的代码。
what do I need to change/add for it work and be able to receive different data types?我需要更改/添加什么才能使其工作并能够接收不同的数据类型?
public static void add(var num){//-here is var but I get an error
//do something
}
I know var is used for doing this but it doesn't work in my code.我知道 var 用于执行此操作,但它在我的代码中不起作用。
No, it is not.不它不是。
Java is strongly and simply typed. Java 是强而简单的类型。 Things have a type.事物是有类型的。 There is no dynamic/ducktyping type.没有动态/鸭式类型。 var
is not that. var
不是这样的。 var is just syntax sugar. var 只是语法糖。
In a ducktyping/dynamic language, you could write:在鸭式/动态语言中,您可以编写:
var x;
x = 5;
x = "Hello";
In java, you cannot do that .在 java 中,您不能这样做。 var x;
is a compiler error.是编译器错误。
var x
in java is just shorthand for: Take the type of the thing you are assigning to x on this very line. java 中的var x
只是简写:在这一行中取你分配给 x 的东西的类型。 Assume I meant that write that type out.假设我的意思是写出那种类型。 In other words, var
is allowed only if you inline initialize:换句话说,仅当您内联初始化时才允许使用var
:
var x = "Hello"; // legal; and 100% the same as writing String x = "Hello"
x = 5; // compiler error. x is of type String, and 5 isn't a string.
what do I need to change/add for it work and be able to receive different data types?我需要更改/添加什么才能使其工作并能够接收不同的数据类型?
What is the common type amongst String, boolean, char, and int? String、boolean、char 和 int 之间的常见类型是什么?
Object
is the best available answer, and it's not a great one. Object
是最好的答案,它不是一个很好的答案。 So that's what you'd have to do:所以这就是你必须做的:
public static void add(Object num) {
if (num instanceof Number) { .... }
else if (num instanceof String) { .... }
else if (num instanceof Boolean) { .... }
else throw new IllegalArgumentException("Only numbers, strings, and booleans allowed");
}
But this is extremely non-java.但这是非常非 java 的。 It sounds like you want to design a weakly typed system, where "5"
and 5
are treated the same, and true
and 1
are treated the same.听起来你想设计一个弱类型系统,其中"5"
和5
被视为相同,而true
和1
被视为相同。 I suggest you don't do that.我建议你不要那样做。
An alternative is to just make that many methods.另一种方法是只制作那么多方法。 In java, a method is defined by its entire signature: The name, but also the param types and return types, as well as the type the method is in. So, you can make more than one add method:在 java 中,方法由其整个签名定义:名称、参数类型和返回类型以及方法所在的类型。因此,您可以创建多个添加方法:
public static void add(String num) { ... }
public static void add(int num) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.