简体   繁体   English

您如何在Java中使用泛型来进行对象的等效转换?

[英]how do you use generics in java to do the equivalent of a cast on an object?

I'm creating an object stack which uses a doubly linked list in order to reference the bottom objects as they are popped off the stack. 我正在创建一个使用双向链接列表的对象堆栈,以便在底部对象从堆栈中弹出时引用它们。 My dilemma is that I have multiple classes which take in objects as parameters. 我的困境是我有多个将对象作为参数的类。 The objects represent instances of the other classes so they are not accepted as parameters into a different class unless the methods and fields of that receiving class are declared with the name of the sending class. 这些对象代表其他类的实例,因此除非将接收类的方法和字段用发送类的名称声明,否则它们不会作为其他类的参数被接受。 I don't want the classes to be dependent off of each other since I want to use the doubly linked list later on in other programs. 我不希望这些类相互依赖,因为我想稍后在其他程序中使用双向链表。 So I am contemplating writing generics into my program or casting the objects. 因此,我正在考虑将泛型写入程序或转换对象。 Which do you think is the better choice and why? 您认为哪个是更好的选择,为什么? Also how would the approach be implemented? 还有该方法将如何实施?

I think you should use generics. 我认为您应该使用泛型。 They are a new feature added to Java 5 for type safety and to prevent inadvertent ClassCastException s. 它们是Java 5中新增的一项新功能,以确保类型安全并防止意外的ClassCastException Here is a basic prototype of a stack implemented using generics: 这是使用泛型实现的堆栈的基本原型:

public class GenericStack<E> {   //'E' is your type parameter, which can be any legal
                                    //identifier, but a capital letter is suggested
    public void push(E obj) {    //use your type parameter name as though it is
                                     //an actual type
        //implementation here
    }

    public E pop() {
        //implementation here
    }
}

If you are going to want to use your stack with many different object types, then generics are very helpful. 如果您想将堆栈与许多不同的对象类型一起使用,那么泛型非常有用。 This would be especially helpful since you say that you will want to use your stack later in other projects, but don't know yet which objects you will want to build the stack with. 这将特别有用,因为您说过以后将要在其他项目中使用堆栈,但是尚不知道要使用哪些对象来构建堆栈。

You can find out more about generics here , but the basic syntax to create such a class would be like this: 您可以在此处找到有关泛型的更多信息,但是创建此类的基本语法如下:

 public class Stack <T>

Where T stands for type. 其中T代表类型。

When you create an object of this class, you will do so like this: 创建此类的对象时,您将像这样进行操作:

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

In place of "Integer", you would put the object type that you will be storing in the class. 代替“ Integer”,您可以将要存储的对象类型放在类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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