简体   繁体   中英

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. 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. 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. The same problem applies with the insert() method, since I don't know what sort of object's being passed in as an argument. In Python there was no need to explicitly state object types in method signatures so this leaves me confused.

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:

http://www.docjar.com/docs/api/java/util/Stack.html

public Object pop(); .

Object is the base class that every class inherits from.

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.

I don't know your setup, so Object pop() may just be your ticket.

EDIT: Or use generics, like duffymo expertly demonstrated.

Java supports generics and allows you to parameterize the type you want to store. 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() {...}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM