简体   繁体   English

访问具有多个对象类型的ArrayList的方法

[英]Accessing Methods of ArrayList with Multiple Object Types in

I've got a superclass that multiple different subclasses extend from. 我有一个扩展了多个不同子类的超类。 Each subclass then has specific methods for that concrete class that other subclasses may not follow. 然后,每个子类都有针对该具体类的特定方法,而其他子类可能不会遵循该方法。 ie: 即:

  • public class NMEA ... methods that all subclasses hold 公共类NMEA ...所有子类都具有的方法
  • public class GPGGASentence extends NMEA .. has some specific method to this type 公共类GPGGASentence扩展了NMEA ..对这种类型有一些特定的方法
  • public class GPGPSSentence extends NMEA .. has some specific method to this type 公共类GPGPSSentence扩展了NMEA ..对此类型有一些特定的方法

I create a subclass by checking the first few letters in the String and then switching between the possibilities. 我通过检查String中的前几个字母,然后在各种可能性之间进行切换来创建子类。

ArrayList<NMEA> sentences = new ArrayList<>();

switch (s.split(",")[0]){
     case "$GPGGA":
          sentences.add(new GPGGASentence(s));
          break;
     case "$GPGPS":
          sentences.add(new GPGPSSentence(s));
          break;
}

I'm now getting to the point I want to loop through this ArrayList. 我现在到达要遍历此ArrayList的地步。 Currently I'm doing the following: 目前,我正在执行以下操作:

for(NMEA nmea : sentences){
     if(nmea instanceof GPGGASentence){
          system.out.println((GPGGASentence) nmea).someSpecificMethod());
     }
 }

I was wondering if their is some nicer way of doing this. 我想知道他们是否是更好的方法。

我对这个问题的解决方案是按照建议将NMEA类更改为抽象类,并列出该类中的所有方法,然后覆盖它们。

Apart from writing abstract class / interface and declaring all the methods, this is what you can do to improve the redability of the code: 除了编写abstract class / interface并声明所有方法之外,您还可以执行以下操作来提高代码的可重复性:

  • Create an enum of all the possible class types 创建所有可能的类类型的enum
  • Write a method that returns enum value for object 编写一个返回对象的枚举值的方法
  • Use switch with different cases. 在不同情况下使用switch

Here is an example. 这是一个例子。 Declare enum like below: 像下面这样声明枚举:

private enum ClassType {
    NMEA,
    GPGGASentence,
    SomeOtherType,
    Unknown;
}

Now, a method to return type : 现在,一个返回type的方法:

private ClassType getClassType(NMEA object){
    ClassType type = null;
    try{
        type = ClassType.valueOf(object.getClass().getSimpleName());
    }catch(IllegalArgumentException e){
        type = ClassType.Unknown;
    }
    return type;
}

Now, use it with switch inside a for loop: 现在,将它与for循环内的switch一起使用:

for(NMEA nmea : sentences){
    switch(getClassType(nmea)){
    case ClassType.NMEA :
        //do something
        break;
    }
}

If a new Impl class gets added in future (or name of any class is changed), all you need to do is to add an enum value and a switch case . 如果将来要添加新的Impl类(或更改任何类的名称),您要做的就是添加一个enum值和一个switch case

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

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