[英]How do I implement a method that returns in Java without knowing what object type I'm returning?
I'm returning to Java after a year spent working with Python, so I'm trying to remember some of the syntax/design techniques involved. 我在使用Python一年后回到Java,所以我试图记住一些涉及的语法/设计技术。 In doing so I'm going back and implementing every project from my previous class, only in Java...yet I'm already stuck on implementing a simple Stack.
在这样做的过程中,我将返回并实现我之前课程中的每个项目,仅限于Java ...但我已经停留在实现一个简单的Stack上了。 This is because I'm not sure how to write method signatures when I don't know what sort of object I'm returning, ie in a pop() method.
这是因为当我不知道我正在返回什么类型的对象时,我不确定如何编写方法签名,即在pop()方法中。 The same problem applies with the insert() method, since I don't know what sort of object's being passed in as an argument.
insert()方法也存在同样的问题,因为我不知道作为参数传递了什么类型的对象。 In Python there was no need to explicitly state object types in method signatures so this leaves me confused.
在Python中,没有必要在方法签名中显式声明对象类型,因此这让我感到困惑。
Do I have to write separate methods for each possible type of argument/return value, or is there some way around this problem? 我是否必须为每种可能的参数/返回值类型编写单独的方法,或者是否有某种解决方法?
You can write it like this: 你可以像这样写:
public interface Stack
{
void push(Object o);
Object pop();
}
Or you can use generics: 或者您可以使用泛型:
public interface Stack<T>
{
void push(T o);
T pop();
}
If your purpose is not to write your own, you can use the one built into Java: 如果你的目的不是自己编写,你可以使用Java内置的:
http://www.docjar.com/docs/api/java/util/Stack.html http://www.docjar.com/docs/api/java/util/Stack.html
public Object pop();
. 。
Object is the base class that every class inherits from. Object是每个类继承的基类。
That said, while this kind of signature has its merits, in many cases a better approach would be something more type-safe, ie popInt(), popString(), etc - after all, the calling code will need to cast the Object to something, and worse still, it needs to make the decision on what to cast it to based on something that is typically better done using polymorphism. 也就是说,虽然这种签名有其优点,但在许多情况下更好的方法是类型安全的东西,即popInt(),popString()等 - 毕竟,调用代码需要将Object转换为事情,更糟糕的是,它需要根据通常使用多态性做得更好的事情做出决定。
I don't know your setup, so Object pop()
may just be your ticket. 我不知道你的设置,所以
Object pop()
可能只是你的票。
EDIT: Or use generics, like duffymo expertly demonstrated. 编辑:或使用泛型,如duffymo专业演示。
Java supports generics and allows you to parameterize the type you want to store. Java支持泛型,并允许您参数化要存储的类型。 So in your case it would be something like.
所以在你的情况下它会是这样的。 Read more on this here
在这里阅读更多内容
public class Stack<T>
{
List<T> items=new ArrayList<T>();
public T push(T item) {...}
public T pop() {...}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.