简体   繁体   English

Java SE 1.3,不能使用泛型。 我用于存储/检索自定义对象的解决方案可以吗?

[英]Java SE 1.3, cant use generics. Is my solution for storing/retrieving a custom object ok?

I have a custom class called Log. 我有一个名为Log的自定义类。 I can't create an arraylist of logs because I can't use generics. 由于无法使用泛型,因此无法创建日志的数组列表。 So, I create a standard arraylist (type object) and commit all of my "logs" to it. 因此,我创建了一个标准的arraylist(类型对象)并将其所有“日志”提交给它。 Then, when iterating over the arraylist later I simply cast "outcoming" objects as logs. 然后,稍后在遍历arraylist时,我仅将“待处理”对象转换为日志。 ie

Log log = (Log) it.next();

Im not sure if this will work... or even if it does if it's the best idea. 我不确定这是否行得通...或者即使是最好的想法也行不通。 Really appreciate any feedback! 非常感谢任何反馈!

Yes it will work. 是的,它将起作用。

In order to be in the safer side you can check whether the object is of type Log using instanceof operator. 为了安全起见,您可以使用instanceof运算符检查对象的类型是否为Log

Ex 防爆

Object obj = it.next();
if( obj instanceof Log){
    Log log = (Log) obj;
    // Do something
} else {
    //Log a warning or error message
}

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

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