-6

i have this code and my question is how can i accses only one element of the array for example mark age

public class App {

    public static void main(String[] args) {
       List<students> here = new ArrayList<>();
       here.add(new students("mark","markos",23,32));

    }
}
MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37

5 Answers5

1

This is not an Array, but a List (albeit an ArrayList being backed by an array internally, but that's implementation detail and slightly beside the point here).

When you add a Student to your list, it becomes an element of that list. You can access List elements using list.get(int index).

"Mark" or 23 in your example are not elements of the list, but properties of the Object "Student" (remember that in Java, class names are CamelCase and usually singular by convention)

Therefore, what I think you want is something like:

Student mark = new Student("Mark", "Markos", 23, 32);
//assuming a constructor exists e.g.:
//Student(String firstname, String lastname, int age, int studentNumber)

here.add(mark);
Student stillMark = here.get(0);   //assuming no other modification
String marksName = mark.getName(); //"Mark", assuming this getter exists
int marksAge = mark.getAge();      //23, ditto

mark.setAge(24); //who's birthday is it?
System.out.println(stillMark.getAge()); //24 - mark and stillMark point to exactly the same object.

These are basic Java (and other programming language) concepts. Good luck with your learning.

Edit: Calculate the average age on Java 8+ (also see Calculating average of an array list?)

OptionalDouble avgAge = list
     .stream()               //Use Java 8 streams to iterate
     .mapToInt(Student::age) //transform into an IntStream
     .average();             //IntStream has this beautiful method
if(avgAge.isPresent()) {
    //this will be false if the list was empty.
}
Thomas Timbul
  • 1,634
  • 6
  • 14
  • yes i know this way soory this is the first time for me using stackoverflow i did not provided you with the completed code – leo20384 Oct 15 '19 at 10:26
  • That's fine, no need to apologise in any way. I've added a sentence about list elements - hope this helps you anyway. – Thomas Timbul Oct 15 '19 at 10:30
  • i have an lis array that store more than 5 people information and i need to get each person age to calculate the average age of the 5 – leo20384 Oct 15 '19 at 10:31
  • If that is your actual question, please update your question. Or you may ask a new one, but I suggest you look here: https://stackoverflow.com/questions/10791568/calculating-average-of-an-array-list Have added an example. – Thomas Timbul Oct 15 '19 at 10:40
0

You can use get method of list:

example:

students student_at_index_zero = here.get(0);

Document: List::get(index)

MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37
0

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.

Hubi
  • 440
  • 1
  • 11
  • 25
0

To get values from array list use the following method. :: get() and pass the index value. So that you will get he desired result.

For Ex: here.get(0);

0

Your example: List here = new ArrayList<>(); here.add(new students("mark","markos",23,32));

Assuming you have a "getName" method in your student class. You can do this to get the name of mark by:

here.get(0).getName();

or you can use the instance variable you have mark stored in:

here.get(0).name;

If you have many students a nice way to access all there names is by using java stream()

    String studentNames = here.stream()
                                .collect(Collectors.groupingBy(Person::getName))
                                .keySet()
                                .stream()
                                .collect(Collectors.joining(" "));
    System.out.println(studentNames);