You're using an ArrayList in this case.
Here you can access the object in the list (if there are no other objects and you know at which index position the object is located) via index 0.
Student mark = here.get(0);
To get the age, the Student class must have a getter (if necessary also setter) method.
With this method you can then access the property age.
String name;
String surename;
int age;
public Student(String name, String surename, int age) {
this.name = name;
this.surename = surename;
this.age = age;
}
public String getName() {
return name;
}
public String getSurename() {
return surename;
}
public int getAge() {
return age;
}
Example:
List<Student> here = new ArrayList<>();
here.add(new Student("mark", "markos", 23));
Student mark = here.get(0);
System.out.println("Studentsname: " + mark.getName() + " and age: " + mark.getAge());
Output:
Studentsname: mark and age: 23
If you want to get the average of the age of all students in the List you can do something like this:
public static void main(String[] args) {
List<Student> here = new ArrayList<>();
here.add(new Student("mark", "markos", 23));
here.add(new Student("Peter", "Pahn", 33));
here.add(new Student("Sarah", "Saraha", 44));
here.add(new Student("Tanja", "Manja", 63));
here.add(new Student("Sven", "Svenson", 48));
System.out.println("Average age of all students in the List: " + averageOfAllStudentsAge(here));
}
Method to calculate average with indexed loop:
public static double averageOfAllStudentsAge(List<Student> students) {
int allAges = 0;
for (int i = 0; i < students.size(); i++) {
Student student = students.get(i);
allAges += student.getAge();
}
return (double) allAges / students.size();
}
Method to calculate average with enhanced loop:
public static double averageOfAllStudentsAge(List<Student> students) {
int allAges = 0;
for (Student student : students) {
allAges += student.getAge();
}
return (double) allAges / students.size();
}
Using streamAPI:
public static double averageOfAllStudentsAge(List<Student> students) {
int allAges = students.stream()
.mapToInt(Student::getAge)
.sum();
return (double) allAges / students.size();
}
maybe that was helpful, and you can move on.