-1
    public class Test {

     
        public static class Data{
            
            List<? extends AbsModel> definitions;
            public Data(List <? extends AbsModel> definitions) {
                this.definitions = definitions;
            }
            
             public List<? extends AbsModel> getDefinitions() {
                    return this.definitions;
                }
        }
            
            public Data getData() {
                
                //code to create different model defnitions that extends MainModel
                ModelDef model1 = new ModelDef();
                ModelDef2 model2 = new ModelDef2();
                final List<AbsModel> createdDefs = new ArrayList<>(); // what should ideally be the generic type here?
                createdDefs.add(model1);
                createdDefs.add(model2); // class cast exception
                Test.Result r = new Test.Result(createdDefs);
                return r;
            }
        }
            

Below is how the inheritance model look like

        class ModelDef extends MainModel{
                
        }
        class MainModel extends AbsModel{
            
        }

        class ModelDef2 extends AbsMainModel{
            
        }
        public abstract class AbsMainModel extends AbsNestableMainModel{
            
        }
        
        public abstract class AbsNestableMainModel extends AbsModel {
            
        }

There will be modeldef and modeldef2 created in getData() method. I want to add these created definition objects to the createdDef list and return the result object.

Can anyone tell me how can I do that?

knittl
  • 216,605
  • 51
  • 293
  • 340
  • 2
    That line shouldn't throw a class cast exception (and it doesn't for me). Are you sure the code you have posted here is equivalent to your real code? – knittl May 17 '22 at 22:10
  • sorry, got my prev comment wrong. Try `final List extends AbsModel> createdDefs` – Taylor May 17 '22 at 22:39
  • As a follow up, this is a good read: https://stackoverflow.com/questions/2723397/what-is-pecs-producer-extends-consumer-super – Taylor May 17 '22 at 22:42
  • ArrayList.add should not be able to throw that exception. Edit your question and include the full stack trace of the exception. – VGR May 18 '22 at 02:47
  • Voting to close because the issue is not reproducible. Please update the code if it indeed is – knittl Jun 03 '22 at 06:56

1 Answers1

0

I actual code was a bit different from the posted. This is resolved.