Vectors - accessing an unknown amount of objects
First time on here, I'm pretty new to java. For college just been learning about vectors and such. I pretty much understand how to store objects in vectors and how to cast them to retrieve values of objects.
In basic form I have a class called students which make student objects with an instance variable called mark.
Theres a question I have thats confusing me. It says that a method will take in a vector as its parameter of student objects. The requirements of the question are then for how many objects there are in the vector (The number of student objects in the vector will be random) that the mark of these students would be displayed. So for example if theres three student objects with marks 20,30,40. These values will be printed out like, "20 30 40"
I understand that I can simply find out the size of the vector with int vecSize=vectorName.size();
But what confuses me is after this how on earth will I be able to retrieve all of these objects as the size of the vector is unknown and number of objects in that vector are unknown?
Any examples or explainations of the best way of doing this are much appreciated.
Re: Vectors - accessing an unknown amount of objects
There are two simple ways:
1. Use an enhanced for loop. This is probably the simpler of the two, but in my opinion limits what you can do concerning the main vector you're dealing with.
for(Student s : students)
// do stuff with s
System.out.println("Student's name: " + s.getName());
The above code can be read as "for each Student s in students, ... (stuff inside the for-each block)
2. The second method is to use a standard for-loop (or a while loop) with a loop counter
for (int i = 0; i < students.size(); i++)
System.out.println("Student " + i + "'s name: " + students.get(i));
As you can see, there are certain things you can do using a loop counter since you do have more information. However, you will need to keep track of the loop counter yourself (not a big deal if it's something simple like this, but can get hairy as you nest multiple loops)