Creating an ArrayList from superclass but containing objects from extended classes
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
add a comment |
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
You can do that if thereis-arelationship between them
– secret super star
Nov 16 '18 at 9:18
1
ifEmailContactandPhoneContactextendContactyou can just add them to theArrayList<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 thegetEmailrespectivelygetPhonemethods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise anClassCastException
– Brad
Nov 16 '18 at 9:33
add a comment |
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
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
java generics arraylist
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 thereis-arelationship between them
– secret super star
Nov 16 '18 at 9:18
1
ifEmailContactandPhoneContactextendContactyou can just add them to theArrayList<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 thegetEmailrespectivelygetPhonemethods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise anClassCastException
– Brad
Nov 16 '18 at 9:33
add a comment |
You can do that if thereis-arelationship between them
– secret super star
Nov 16 '18 at 9:18
1
ifEmailContactandPhoneContactextendContactyou can just add them to theArrayList<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 thegetEmailrespectivelygetPhonemethods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise anClassCastException
– 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
add a comment |
4 Answers
4
active
oldest
votes
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());
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
add a comment |
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{
}
add a comment |
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);
add a comment |
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;
}
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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());
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
add a comment |
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());
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
add a comment |
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());
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());
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
add a comment |
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
add a comment |
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{
}
add a comment |
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{
}
add a comment |
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{
}
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{
}
answered Nov 16 '18 at 9:21
secret super starsecret super star
1,026316
1,026316
add a comment |
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
answered Nov 16 '18 at 9:23
nits.kknits.kk
3,47431840
3,47431840
add a comment |
add a comment |
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;
}
add a comment |
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;
}
add a comment |
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;
}
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;
}
edited Nov 16 '18 at 9:44
answered Nov 16 '18 at 9:23
Nicholas KNicholas K
8,46671739
8,46671739
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
You can do that if there
is-arelationship between them– secret super star
Nov 16 '18 at 9:18
1
if
EmailContactandPhoneContactextendContactyou can just add them to theArrayList<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
getEmailrespectivelygetPhonemethods, only if you explicitly cast the contacts retrieved to their expected Class, which will often raise anClassCastException– Brad
Nov 16 '18 at 9:33