Syrenthia
Syrenthia

Reputation: 144

How to add something to an element of an arraylist?

I'm trying to add a grade to my arraylist object, when I tried to add two different grades to two different arraylist objects, evetything looks okay but when I try to print both objects, it prints like both grades belongs to same object. You will understand when you see the sample execution.

This is in my main method.

Student s1 = new Student("Cuneyt Cakir", "Istanbul", 35);
Student s2 = new Student("Halis Ozkahya", "Yalova", 28);
Student s3 = new Student("Mustafa Kamil Abitoglu", "Antalya", 20);
s1.addGrade(15);
s1.addGrade(89);
s1.addGrade(26);
s1.addGrade(44);
s2.addGrade(33);
System.out.println(s1);
System.out.println(s2);

The result is:

Name: Cuneyt Cakir / City: Istanbul / Age: 35
Grades: [15, 89, 26, 44, 33]
Name: Halis Ozkahya / City: Yalova / Age: 28
Grades: [15, 89, 26, 44, 33]

This is my add method in Students class:

public static void addGrade(int grade) {
    if(grade>=0 && grade<=100){
        grades.add(grade);
    } else
        System.out.println("Invalid grade.");
}

This is another part of Student class:

public static ArrayList<Integer> grades=new ArrayList<Integer>();

public Student(String value1, String value2, int value3) {
    name=value1;
    city=(value2);
    age=(value3);
}

And I'm getting grades with this code:

public ArrayList<Integer> getGrades() {
    return grades;
}

The expected output is:

Name: Cuneyt Cakir / City: Istanbul / Age: 35
Grades: [15, 89, 26, 44]

Name: Halis Ozkahya / City: Yalova / Age: 28
Grades: [33]

Upvotes: 0

Views: 321

Answers (2)

user2887201
user2887201

Reputation: 337

Remove static modifier,

public static ArrayList<Integer> grades=new ArrayList<Integer>();

Change to,

public ArrayList<Integer> grades=new ArrayList<Integer>();

Static modifier makes "grades" a class member. Removing static makes it an instance member

Upvotes: 1

K139
K139

Reputation: 3669

Its because grades is a static variable. Remove 'static' keyword to create a new ArrayList instance for each object.

Static variables in a class are common to all objects. So `grades' variable is common to all S1, S2 and S3 instances.

Upvotes: 2

Related Questions