-
need help in ArrayList
Example Question :
• A constructor (with parameters) that assigns values to all data members.
• Getters for all of the data members above.
• A private static ArrayList named list that holds a list of Student objects.
• A static getter named getList() that returns the ArrayList above.
The things i have done :
public class Student{
String name;
String gender;
int year;
String[] countries;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
I want to ask how to do the "ArrayList named list that holds a list of Student objects" and did i do any things wrong in declaring the variable for Student?:(:(
-
Do you know how to declare a static variable? And do you know how to use ArrayList? Basically, what the part you've emphasized is asking is to declare a static variable named list, and that is an ArrayList type object meant to hold Student objects.
Here's a couple links to help you:
Understanding Instance and Class Members (The Java™ Tutorials > Learning the Java Language > Classes and Objects) (on static variables)
Java: ArrayList (on ArrayList stuff--you can see him creating and modifying ArrayLists here)
-
i still confusing with it :( can you make some simple example for me for the 4steps?(name+gender)
-
If you clicked the links I provided, you'd find examples of everything you have to do. All that's left is for you to put 2 and 2 together. I can't sit behind you and help you during an exam--if you don't bother to learn HOW to do it, you're not going to have a whole lot of luck in the future, I'm afraid.
-
You better make your class variables as private.It makes some sense in your class.
-
• A private static ArrayList named list that holds a list of Student objects.
import java.util.ArrayList;
public class Student{
private static ArrayList<Student> list = new ArrayList<Student>();
}
If I am wrong with this statement please help me do some correction.
Thank you..^^
-
Code:
public class ListEx {
public static void main(String[] args) {
new Student("mak","male");
new Student("pandian","male");
new Student("nithya","female");
ArrayList list=Student.getList();
for(Object o : list){
Student s=(Student)o;
System.out.println(s.getName());
System.out.println(s.getGender());
}
}
}
class Student {
private String name;
private String gender;
private static ArrayList<Student> list=new ArrayList<Student>();
public Student(String name,String gen) {
this.gender=gen;
this.name=name;
list.add(this);
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public static ArrayList getList() {
return list;
}
}
Hope this helps..