-1

I have an arraylist called election(). Why isn't code this reassigning the name variable like it should.

private static void replaceName(String oldName, String newName){
    Candidate c;
    for(int i = 0;i<election().size();i++){
        c = election().get(i);
        if(c.name == oldName){
            election().get(0).name = newName;
            System.out.println(election().get(0).getName());
        }
    }
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
CarbonZonda
  • 167
  • 2
  • 11

1 Answers1

1

You are incorrectly comparing strings in your if statement. Instead of c.name == oldName, it should be c.name.equals(oldName).

Also, you're assigning the new name to the wrong object.

Instead of elections.get(0).name = newName, it should be c.name = newName since c is a reference to the object stored in your ArrayList. Changes made to c will be reflected in your list. Your current code changes the name of the first candidate in your ArrayList, since you always call get() with 0 rather than i.

Anish Goyal
  • 2,799
  • 12
  • 17