Java using generics with lists and interfaces

后端 未结 6 1747
遇见更好的自我
遇见更好的自我 2021-01-13 11:02

Ok, so here is my problem:

I have a list containing interfaces - List a - and a list of interfaces that extend that interface: Li

6条回答
  •  感情败类
    2021-01-13 11:41

    THIS WORK, BUT YOU SHOULD BE WARN !!!!

    @Override
    // Patient is Interface
    public List getAllPatients() {
    
       // patientService.loadPatients() returns a list of subclasess of Interface Patient
       return (List)(List)patientService.loadPatients(); 
    }
    

    You can cast from List of Objects to List of Interface in this way. But, if you get this list somewhere in your code and if you try to add something to this list, what would you add? Inteface or Subclass of this interface ? You actually loose information of the type of list, because you let it hold Interface, so you can add anything that implement this interface, but the list is holding the subclasses only, and you could easily get class cast exception if you try to do operations like add or get on this list with some other subclass. The solution is: Change The type of source list to list instead of cast, then you are free to go :)

提交回复
热议问题