I'm trying to store an object person in an ArrayList.
I have an ArrayList<String> customer = new ArrayList<String>();
The object 'person' has two variables: name (String) and pNr (long).
I have tried to simply add it: customer.add(person)
but that doesn't seem to work.
To clarify: I don't want to store the variables individually. I want to store the entire object person in the ArrayList.
I simply can't figure out how to engage this problem or even if it can be done.
Can someone point me in the right direction?
Change your List
such that it accepts a Person object instead of a String
.
List<Person> customer = new ArrayList<Person>();
Person person = ......;
customer.add(person);
Person Class
public class Person {
String name;
long pNr;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getPNR() {
return pNr;
}
public void setPNR(long pNr) {
this.pNr = pNr;
}
}
Creating a Person Object
Person person = new Person();
person.setName("Name");
person.setPNR(pNr);
Adding to ArrayList
ArrayList<Person> personList = new ArrayList<Person>();
personList.add(person);
Retrieving Data
String selectedName = personList.get(i).getName();
You need to use a List
with a different generic type. Since the generic type specified on your current List
is String
it will only allow you to add objects of type String
into the list.
List<Person> customer = new ArrayList<Person>();
I would also recommend using the List
interface in case the need would arise to switch to a different implementation such as LinkedList
.
Look at this
import java.util.ArrayList;
import java.util.List;
public class Tester4 {
public static void main(String args[]) {
List<Person> persons = new ArrayList<Person>();
Person person = new Person();
person.setName("Tester");
person.setPersonNr(1245L);
persons.add(person);
person = new Person();
person.setName("Tester 2");
person.setPersonNr(1299L);
persons.add(person);
}
}
class Person {
private String name;
private Long personNr;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getPersonNr() {
return personNr;
}
public void setPersonNr(Long personNr) {
this.personNr = personNr;
}
}
ArrayList<String> customer = new ArrayList<String>();
in this way you defined that the arrayList customer
accept type String
only.
ArrayList<Person> customer = new ArrayList<Person>();
this will only accept object with Person
type (and subType of Person).
define a class Person
public class Person(){
private String name;
private long pNr;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public long getPNR(){
return pNr;
}
public void setPNR(long pNr){
this.pNr = pNr;
}
}
then you use a:
ArrayList<Person> customer = new ArrayList<Person>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With