0

I'm sorry if the question is unnecessary or if the problem is obvious, but I've tried to solve this for several hours and I'm running out of ideas.

public List<Letter> convertToList(char[] array){
  List<Letter> result = new ArrayList<>();
  for(int i = 0; i < array.length; i++){
    result.add(new Letter(array[i]));
  }
  return result;
}

Here's the code of the Letter class:

public class Letter{
    private static char content; 
    private boolean guessed = false;
    public Letter(char content){
        this.content = content;
    }
    public char getContent(){
        return this.content;
    }
}

The result of running the covertToList() method is a List, which contains different Letter objects, which all have the same content. For example, if I pass in an array a = [T, E, S, T], the function will return a List with different Letter objects, which all have the content "T". I found out that the list is overwritten in every step, so in the first iteration, the List is [T], in the second it's [E, E].

I feel kind of stupid for not seeing the issue. Can someone help?

1 Answers1

-1

The problem is that the content field in the Letter class is defined static. A static field is common to all instances of a class.

So when you create a new instance you are setting the common content field to all instances of that class.

You can simply remove the keyword static in front of the definition

public class Letter {
    // Removed the keyword static here
    private char content; 
    private boolean guessed = false;
    public Letter(char content){
        this.content = content;
    }
    public char getContent(){
        return this.content;
    }
}

You can find a complete official definition of the keyword static here where is stated:

In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • Not sure, but it _might_ be because this is a common duplicate, and answering common duplicates is frowned upon. – Ivar Sep 21 '21 at 07:46