简体   繁体   中英

Java Generics: How to avoid a mess in class header

I am working with java generics and I want to avoid a mess in my class headers.

// The car saves a generic list
class Car<L>{
 ArrayList<L> exampleList=new ArrayList();

 public void ArrayList<L> getExampleList(){
    return exampleList;
 }
}


class Mercedes extends Car<Engines> ...
class Porsche extends Car <Wheels>... 


class Warehouse<T extends Car>{
    T car;

    // I want to work with a generic List here
    public void useListFromCar(){
          // This returns a simple ArrayList but not a ArrayList<L> 
          car.getExampleList();

    }
}


I need to be able to work with a generic list, not just a ArrayList. The only way I know of to solve this results in a mess in my class headers. Also, it would be redudant information in the header. The specific child car already knows the type of the List. Why should the Warehouse need to know about that.

// Redundant and messy header :(
class Warehouse<L, T extends Car<L>>{
    T car;


    public void useListFromCar(){
          // This returns the desired ArrayList<L> 
          car.getExampleList();

    }
}

I think you can imagine that this becomes quite unmanageable with bigger classes. Is there a way to avoid this?

the way you have done does't have problem. the problem is the way you abstract it:

why Cars have generic type such as Engines, Wheel for different brand? Engines and Wheels are cars' components. you can write several interfaces named Engine, Wheel, and implement concrete classes of them. in your Car class, it should contains these components. and the generic type could be brand name. all the codes are generated from the real world common sense. if you write something that doesn't make sense, then it will be in a mess for sure.

here is a sensible example:

interface Car<L>{
     List<Wheel> wheels;
     Engine engin;
       //get set method
}

interface Wheel{
    String getBrand();
    String getquality();
...
}
interface Engine{
    String getHorsePower();
    String getSize();
...
}
class MuscleCar implements Car<Mercedes>{
...
}
class RacingCar implements Car<Mercedes>{
...
}




class Warehouse<T extends Car>{
    List<T> cars;

    // I want to work with a generic List here
    public void useListFromCar(){
          // This returns a simple ArrayList but not a ArrayList<L> 
         for(T car: cars){
           car.getBrand();
           car.getType();
           car.getEngine(); //etc..
        }
    }
}

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