Use of ArrayList in Java to store Name and Age
I want to add both String and Integer type of value in ArrayList.
For example i have array list in which i want to add name of the persons and age of the corresponding person in a single arralist.
How can i accomplish this. How can i get this? Actually i am retrievin开发者_Python百科g data from database and want to save all the employee names and ages in a single array list. Like multidimensional array list.
Create a a person class with age and name, then create an ArrayList of that type.
class Person {
private String mName;
private int mAge;
public Person(int age, String name) {
mName = name;
mAge = age;
}
public String getName() {
return mName;
}
etc ........
}
ArrayList<Person> arr = new ArrayList<Person>();
arr.add(new Person(10, "joe"));
You should create a class to represent a person and then add those to a list. It's a bad practice to mix the type of objects in a list. You could start with a simple person class:
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Then create a list like this:
List<Person> people = new ArrayList<Person>();
And add people that you read from the database to the list:
people.add(new Person(name, age));
You can use the simple ArrayList
and add the boxed type of int
, Integer
along with String
.
You can make a Person Class
class Person{
String name;
int age;
//Add the getteres and setters
}
Then declare an arrayList as follows.
ArrayList<Person> p = new ArrayList<Person>();
Then for each person create a person object and populate the arrayList as follows.
p.add(personObj);
You can create an ArrayList<Object>
. Both Integer
and String
are subclasses of Object
, and so both can be added to an ArrayList<Object>
.
That said, it seems unlikely to me that you'd really want to do this. An ArrayList
is a list. It's generally a bad smell (ie: a sign of a poor design) if you're storing things in a list that aren't the same kind of thing in some sense.
Having a correspondence between elements as you describe suggests that you actually want a list of employee objects, where each employee object has a name and an age.
Another possibility would be to use a Map
if the names are unique. You can use a LinkedHashMap
if you care about preserving order.
class Employee{
int age;
String name;
//+acessor method
}
Lit<Employee> list = new ArrayList<Employee>();
To make sure the compiler doesn't complain, use Generics to specify that you want to add Objects to your ArrayList; this will let you add both types Integer and String to it:
ArrayList<Object> myList = new ArrayList<Object>();
Then you can add your objects of either type to it.
However, Java is strongly-typed for a reason, so the need to add two types into one ArrayList suggests a design problem to me.
精彩评论