Creating an ArrayList from superclass but containing objects from extended classes












0















I have 3 classes. Contact, EmailContact, and PhoneContact. I want to create an Arraylist that can contain objects from both EmailContact and PhoneContact. And i need to find a way to get those objects. Here is what i have so far but It doesn't seem to split them like i wanted to.



    public void addEmailContact(String date, String email) {
ArrayList<Contact> con = new ArrayList<>();
con.add(new Contact(date, email));
}

public void addPhoneContact(String date, String phone) {
ArrayList<Contact> con = new ArrayList<>();
con.add(new Contact(date, phone));
}









share|improve this question

























  • You can do that if there is-a relationship between them

    – secret super star
    Nov 16 '18 at 9:18






  • 1





    if EmailContact and PhoneContact extend Contact you can just add them to the ArrayList<Contact> list

    – migron
    Nov 16 '18 at 9:18













  • con.add(new EmailContact(date, email)); instead

    – Trung NT Nguyen
    Nov 16 '18 at 9:19













  • @TrungNTNguyen Thank you for this.

    – Stefan
    Nov 16 '18 at 9:28











  • what do you want to do with the array content? as it will be awkward when retrieving objects because you will not really know if it's an EmailContact or PhoneContact, and more so you will not be able to use the getEmail respectively getPhone methods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise an ClassCastException

    – Brad
    Nov 16 '18 at 9:33
















0















I have 3 classes. Contact, EmailContact, and PhoneContact. I want to create an Arraylist that can contain objects from both EmailContact and PhoneContact. And i need to find a way to get those objects. Here is what i have so far but It doesn't seem to split them like i wanted to.



    public void addEmailContact(String date, String email) {
ArrayList<Contact> con = new ArrayList<>();
con.add(new Contact(date, email));
}

public void addPhoneContact(String date, String phone) {
ArrayList<Contact> con = new ArrayList<>();
con.add(new Contact(date, phone));
}









share|improve this question

























  • You can do that if there is-a relationship between them

    – secret super star
    Nov 16 '18 at 9:18






  • 1





    if EmailContact and PhoneContact extend Contact you can just add them to the ArrayList<Contact> list

    – migron
    Nov 16 '18 at 9:18













  • con.add(new EmailContact(date, email)); instead

    – Trung NT Nguyen
    Nov 16 '18 at 9:19













  • @TrungNTNguyen Thank you for this.

    – Stefan
    Nov 16 '18 at 9:28











  • what do you want to do with the array content? as it will be awkward when retrieving objects because you will not really know if it's an EmailContact or PhoneContact, and more so you will not be able to use the getEmail respectively getPhone methods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise an ClassCastException

    – Brad
    Nov 16 '18 at 9:33














0












0








0








I have 3 classes. Contact, EmailContact, and PhoneContact. I want to create an Arraylist that can contain objects from both EmailContact and PhoneContact. And i need to find a way to get those objects. Here is what i have so far but It doesn't seem to split them like i wanted to.



    public void addEmailContact(String date, String email) {
ArrayList<Contact> con = new ArrayList<>();
con.add(new Contact(date, email));
}

public void addPhoneContact(String date, String phone) {
ArrayList<Contact> con = new ArrayList<>();
con.add(new Contact(date, phone));
}









share|improve this question
















I have 3 classes. Contact, EmailContact, and PhoneContact. I want to create an Arraylist that can contain objects from both EmailContact and PhoneContact. And i need to find a way to get those objects. Here is what i have so far but It doesn't seem to split them like i wanted to.



    public void addEmailContact(String date, String email) {
ArrayList<Contact> con = new ArrayList<>();
con.add(new Contact(date, email));
}

public void addPhoneContact(String date, String phone) {
ArrayList<Contact> con = new ArrayList<>();
con.add(new Contact(date, phone));
}






java generics arraylist






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 17 '18 at 18:46









Nicholas K

8,46671739




8,46671739










asked Nov 16 '18 at 9:15









StefanStefan

13116




13116













  • You can do that if there is-a relationship between them

    – secret super star
    Nov 16 '18 at 9:18






  • 1





    if EmailContact and PhoneContact extend Contact you can just add them to the ArrayList<Contact> list

    – migron
    Nov 16 '18 at 9:18













  • con.add(new EmailContact(date, email)); instead

    – Trung NT Nguyen
    Nov 16 '18 at 9:19













  • @TrungNTNguyen Thank you for this.

    – Stefan
    Nov 16 '18 at 9:28











  • what do you want to do with the array content? as it will be awkward when retrieving objects because you will not really know if it's an EmailContact or PhoneContact, and more so you will not be able to use the getEmail respectively getPhone methods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise an ClassCastException

    – Brad
    Nov 16 '18 at 9:33



















  • You can do that if there is-a relationship between them

    – secret super star
    Nov 16 '18 at 9:18






  • 1





    if EmailContact and PhoneContact extend Contact you can just add them to the ArrayList<Contact> list

    – migron
    Nov 16 '18 at 9:18













  • con.add(new EmailContact(date, email)); instead

    – Trung NT Nguyen
    Nov 16 '18 at 9:19













  • @TrungNTNguyen Thank you for this.

    – Stefan
    Nov 16 '18 at 9:28











  • what do you want to do with the array content? as it will be awkward when retrieving objects because you will not really know if it's an EmailContact or PhoneContact, and more so you will not be able to use the getEmail respectively getPhone methods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise an ClassCastException

    – Brad
    Nov 16 '18 at 9:33

















You can do that if there is-a relationship between them

– secret super star
Nov 16 '18 at 9:18





You can do that if there is-a relationship between them

– secret super star
Nov 16 '18 at 9:18




1




1





if EmailContact and PhoneContact extend Contact you can just add them to the ArrayList<Contact> list

– migron
Nov 16 '18 at 9:18







if EmailContact and PhoneContact extend Contact you can just add them to the ArrayList<Contact> list

– migron
Nov 16 '18 at 9:18















con.add(new EmailContact(date, email)); instead

– Trung NT Nguyen
Nov 16 '18 at 9:19







con.add(new EmailContact(date, email)); instead

– Trung NT Nguyen
Nov 16 '18 at 9:19















@TrungNTNguyen Thank you for this.

– Stefan
Nov 16 '18 at 9:28





@TrungNTNguyen Thank you for this.

– Stefan
Nov 16 '18 at 9:28













what do you want to do with the array content? as it will be awkward when retrieving objects because you will not really know if it's an EmailContact or PhoneContact, and more so you will not be able to use the getEmail respectively getPhone methods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise an ClassCastException

– Brad
Nov 16 '18 at 9:33





what do you want to do with the array content? as it will be awkward when retrieving objects because you will not really know if it's an EmailContact or PhoneContact, and more so you will not be able to use the getEmail respectively getPhone methods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise an ClassCastException

– Brad
Nov 16 '18 at 9:33












4 Answers
4






active

oldest

votes


















4














Wildcards are here to help you. One can add any class that extends Contact class to a list which accepts ? super Contact



List<? super Contact> list= new ArrayList<>();
list.add(new EmailContact());
list.add(new PhoneContact());





share|improve this answer
























  • Thank you for this. Do you know how can i get them separately in different methods?

    – Stefan
    Nov 16 '18 at 9:33











  • Both methods need to share same list, take it as a parameter or declare it as instance variable

    – nits.kk
    Nov 16 '18 at 12:06











  • @nits.kk can you elaborate a bit please? I'm new to java and don't quite understand your logic.

    – Stefan
    Nov 16 '18 at 13:12



















2














import java.util.ArrayList;
import java.util.List;

public class Contact {


public static void main(String args) {
List<? super Contact> list = new ArrayList<>();
list.add(new PContact());
list.add(new EContact());

}
}

class PContact extends Contact{

}
class EContact extends Contact{

}





share|improve this answer































    0














    This is basic polymorphism in action. Reference can be of super type but it can refer to object of any sub type. The keyword new instantiates an Object. You need to provide the actual implementation with new. In your case



     Contact con = new PhoneContact(date, phone);
    Contact anotherCon = new EmailContact(date, email);


    So now with ArrayList you can do as below.



    List<Contact> list = new ArrayList<>();
    list.add(new EmailContact(date,email);
    list.add(new PhoneContact(date,phone);





    share|improve this answer































      0














      Assuming this is the hierarchy :



      abstract class Contact { }

      class EmailContact extends Contact { }

      class PhoneContact extends Contact { }


      you can do the following :



      List<? super Contact> myList = new ArrayList<>();
      myList.add(new EmailContact());
      myList.add(new PhoneContact());


      The wildcard signifies that you can add any class that extends Contact to the list.



      Do note that when you fetch an element from myList, the only guarantee is that it will return a type of Object. So do not try to cast it without checking the right instance of Contact otherwise you will end up with a ClassCastException.



      For eg:



      Object contact = myList.get(0);        
      if (contact instanceof EmailContact) {
      EmailContact emailContact = (EmailContact) contact;
      } else if (contact instanceof PhoneContact) {
      PhoneContact phoneContact = (PhoneContact) contact;
      }





      share|improve this answer


























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334707%2fcreating-an-arraylist-from-superclass-but-containing-objects-from-extended-class%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        4














        Wildcards are here to help you. One can add any class that extends Contact class to a list which accepts ? super Contact



        List<? super Contact> list= new ArrayList<>();
        list.add(new EmailContact());
        list.add(new PhoneContact());





        share|improve this answer
























        • Thank you for this. Do you know how can i get them separately in different methods?

          – Stefan
          Nov 16 '18 at 9:33











        • Both methods need to share same list, take it as a parameter or declare it as instance variable

          – nits.kk
          Nov 16 '18 at 12:06











        • @nits.kk can you elaborate a bit please? I'm new to java and don't quite understand your logic.

          – Stefan
          Nov 16 '18 at 13:12
















        4














        Wildcards are here to help you. One can add any class that extends Contact class to a list which accepts ? super Contact



        List<? super Contact> list= new ArrayList<>();
        list.add(new EmailContact());
        list.add(new PhoneContact());





        share|improve this answer
























        • Thank you for this. Do you know how can i get them separately in different methods?

          – Stefan
          Nov 16 '18 at 9:33











        • Both methods need to share same list, take it as a parameter or declare it as instance variable

          – nits.kk
          Nov 16 '18 at 12:06











        • @nits.kk can you elaborate a bit please? I'm new to java and don't quite understand your logic.

          – Stefan
          Nov 16 '18 at 13:12














        4












        4








        4







        Wildcards are here to help you. One can add any class that extends Contact class to a list which accepts ? super Contact



        List<? super Contact> list= new ArrayList<>();
        list.add(new EmailContact());
        list.add(new PhoneContact());





        share|improve this answer













        Wildcards are here to help you. One can add any class that extends Contact class to a list which accepts ? super Contact



        List<? super Contact> list= new ArrayList<>();
        list.add(new EmailContact());
        list.add(new PhoneContact());






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 9:19









        Dark KnightDark Knight

        6,41442850




        6,41442850













        • Thank you for this. Do you know how can i get them separately in different methods?

          – Stefan
          Nov 16 '18 at 9:33











        • Both methods need to share same list, take it as a parameter or declare it as instance variable

          – nits.kk
          Nov 16 '18 at 12:06











        • @nits.kk can you elaborate a bit please? I'm new to java and don't quite understand your logic.

          – Stefan
          Nov 16 '18 at 13:12



















        • Thank you for this. Do you know how can i get them separately in different methods?

          – Stefan
          Nov 16 '18 at 9:33











        • Both methods need to share same list, take it as a parameter or declare it as instance variable

          – nits.kk
          Nov 16 '18 at 12:06











        • @nits.kk can you elaborate a bit please? I'm new to java and don't quite understand your logic.

          – Stefan
          Nov 16 '18 at 13:12

















        Thank you for this. Do you know how can i get them separately in different methods?

        – Stefan
        Nov 16 '18 at 9:33





        Thank you for this. Do you know how can i get them separately in different methods?

        – Stefan
        Nov 16 '18 at 9:33













        Both methods need to share same list, take it as a parameter or declare it as instance variable

        – nits.kk
        Nov 16 '18 at 12:06





        Both methods need to share same list, take it as a parameter or declare it as instance variable

        – nits.kk
        Nov 16 '18 at 12:06













        @nits.kk can you elaborate a bit please? I'm new to java and don't quite understand your logic.

        – Stefan
        Nov 16 '18 at 13:12





        @nits.kk can you elaborate a bit please? I'm new to java and don't quite understand your logic.

        – Stefan
        Nov 16 '18 at 13:12













        2














        import java.util.ArrayList;
        import java.util.List;

        public class Contact {


        public static void main(String args) {
        List<? super Contact> list = new ArrayList<>();
        list.add(new PContact());
        list.add(new EContact());

        }
        }

        class PContact extends Contact{

        }
        class EContact extends Contact{

        }





        share|improve this answer




























          2














          import java.util.ArrayList;
          import java.util.List;

          public class Contact {


          public static void main(String args) {
          List<? super Contact> list = new ArrayList<>();
          list.add(new PContact());
          list.add(new EContact());

          }
          }

          class PContact extends Contact{

          }
          class EContact extends Contact{

          }





          share|improve this answer


























            2












            2








            2







            import java.util.ArrayList;
            import java.util.List;

            public class Contact {


            public static void main(String args) {
            List<? super Contact> list = new ArrayList<>();
            list.add(new PContact());
            list.add(new EContact());

            }
            }

            class PContact extends Contact{

            }
            class EContact extends Contact{

            }





            share|improve this answer













            import java.util.ArrayList;
            import java.util.List;

            public class Contact {


            public static void main(String args) {
            List<? super Contact> list = new ArrayList<>();
            list.add(new PContact());
            list.add(new EContact());

            }
            }

            class PContact extends Contact{

            }
            class EContact extends Contact{

            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 16 '18 at 9:21









            secret super starsecret super star

            1,026316




            1,026316























                0














                This is basic polymorphism in action. Reference can be of super type but it can refer to object of any sub type. The keyword new instantiates an Object. You need to provide the actual implementation with new. In your case



                 Contact con = new PhoneContact(date, phone);
                Contact anotherCon = new EmailContact(date, email);


                So now with ArrayList you can do as below.



                List<Contact> list = new ArrayList<>();
                list.add(new EmailContact(date,email);
                list.add(new PhoneContact(date,phone);





                share|improve this answer




























                  0














                  This is basic polymorphism in action. Reference can be of super type but it can refer to object of any sub type. The keyword new instantiates an Object. You need to provide the actual implementation with new. In your case



                   Contact con = new PhoneContact(date, phone);
                  Contact anotherCon = new EmailContact(date, email);


                  So now with ArrayList you can do as below.



                  List<Contact> list = new ArrayList<>();
                  list.add(new EmailContact(date,email);
                  list.add(new PhoneContact(date,phone);





                  share|improve this answer


























                    0












                    0








                    0







                    This is basic polymorphism in action. Reference can be of super type but it can refer to object of any sub type. The keyword new instantiates an Object. You need to provide the actual implementation with new. In your case



                     Contact con = new PhoneContact(date, phone);
                    Contact anotherCon = new EmailContact(date, email);


                    So now with ArrayList you can do as below.



                    List<Contact> list = new ArrayList<>();
                    list.add(new EmailContact(date,email);
                    list.add(new PhoneContact(date,phone);





                    share|improve this answer













                    This is basic polymorphism in action. Reference can be of super type but it can refer to object of any sub type. The keyword new instantiates an Object. You need to provide the actual implementation with new. In your case



                     Contact con = new PhoneContact(date, phone);
                    Contact anotherCon = new EmailContact(date, email);


                    So now with ArrayList you can do as below.



                    List<Contact> list = new ArrayList<>();
                    list.add(new EmailContact(date,email);
                    list.add(new PhoneContact(date,phone);






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 16 '18 at 9:23









                    nits.kknits.kk

                    3,47431840




                    3,47431840























                        0














                        Assuming this is the hierarchy :



                        abstract class Contact { }

                        class EmailContact extends Contact { }

                        class PhoneContact extends Contact { }


                        you can do the following :



                        List<? super Contact> myList = new ArrayList<>();
                        myList.add(new EmailContact());
                        myList.add(new PhoneContact());


                        The wildcard signifies that you can add any class that extends Contact to the list.



                        Do note that when you fetch an element from myList, the only guarantee is that it will return a type of Object. So do not try to cast it without checking the right instance of Contact otherwise you will end up with a ClassCastException.



                        For eg:



                        Object contact = myList.get(0);        
                        if (contact instanceof EmailContact) {
                        EmailContact emailContact = (EmailContact) contact;
                        } else if (contact instanceof PhoneContact) {
                        PhoneContact phoneContact = (PhoneContact) contact;
                        }





                        share|improve this answer






























                          0














                          Assuming this is the hierarchy :



                          abstract class Contact { }

                          class EmailContact extends Contact { }

                          class PhoneContact extends Contact { }


                          you can do the following :



                          List<? super Contact> myList = new ArrayList<>();
                          myList.add(new EmailContact());
                          myList.add(new PhoneContact());


                          The wildcard signifies that you can add any class that extends Contact to the list.



                          Do note that when you fetch an element from myList, the only guarantee is that it will return a type of Object. So do not try to cast it without checking the right instance of Contact otherwise you will end up with a ClassCastException.



                          For eg:



                          Object contact = myList.get(0);        
                          if (contact instanceof EmailContact) {
                          EmailContact emailContact = (EmailContact) contact;
                          } else if (contact instanceof PhoneContact) {
                          PhoneContact phoneContact = (PhoneContact) contact;
                          }





                          share|improve this answer




























                            0












                            0








                            0







                            Assuming this is the hierarchy :



                            abstract class Contact { }

                            class EmailContact extends Contact { }

                            class PhoneContact extends Contact { }


                            you can do the following :



                            List<? super Contact> myList = new ArrayList<>();
                            myList.add(new EmailContact());
                            myList.add(new PhoneContact());


                            The wildcard signifies that you can add any class that extends Contact to the list.



                            Do note that when you fetch an element from myList, the only guarantee is that it will return a type of Object. So do not try to cast it without checking the right instance of Contact otherwise you will end up with a ClassCastException.



                            For eg:



                            Object contact = myList.get(0);        
                            if (contact instanceof EmailContact) {
                            EmailContact emailContact = (EmailContact) contact;
                            } else if (contact instanceof PhoneContact) {
                            PhoneContact phoneContact = (PhoneContact) contact;
                            }





                            share|improve this answer















                            Assuming this is the hierarchy :



                            abstract class Contact { }

                            class EmailContact extends Contact { }

                            class PhoneContact extends Contact { }


                            you can do the following :



                            List<? super Contact> myList = new ArrayList<>();
                            myList.add(new EmailContact());
                            myList.add(new PhoneContact());


                            The wildcard signifies that you can add any class that extends Contact to the list.



                            Do note that when you fetch an element from myList, the only guarantee is that it will return a type of Object. So do not try to cast it without checking the right instance of Contact otherwise you will end up with a ClassCastException.



                            For eg:



                            Object contact = myList.get(0);        
                            if (contact instanceof EmailContact) {
                            EmailContact emailContact = (EmailContact) contact;
                            } else if (contact instanceof PhoneContact) {
                            PhoneContact phoneContact = (PhoneContact) contact;
                            }






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 16 '18 at 9:44

























                            answered Nov 16 '18 at 9:23









                            Nicholas KNicholas K

                            8,46671739




                            8,46671739






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53334707%2fcreating-an-arraylist-from-superclass-but-containing-objects-from-extended-class%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                The Sandy Post

                                Danny Elfman

                                Pages that link to "Head v. Amoskeag Manufacturing Co."