0

I have created a class named Titles and i have an attribute in it called 'name', which is a String.

class Title{
   String name;
   Title(String name){
       this.name = name;
}

I am looking for words that fit my puprose in a textfile and then I create an object of type Title with this word as an argument, like this (titles is a List containing all the created objects):

while(in.hasNextLine()) {           
            line = in.nextLine();           
            Matcher m = libPattern.matcher(line);           
            while(m.find()) {               
                String token = m.group(1);
                Title newTitle = new Title(token);                      
                if(!titles.contains(newTtile)) {                    
                    titles.add(newTitle);                   
                    System.out.println(newTitle.getName());
                }

            }

I have overrided the equals and hashCode methods with the standard way:

@Override
public boolean equals(Object o) {
    if(o == null)
        return false;
    if(o == this)
        return true;
    if(!(o instanceof Title))
        return false;
    Title t = (Title) o;
    return t.getName() == this.getName();
}

@Override
public int hashCode() {
    return this.getName().hashCode();
}

Now my problem is that although I check if the titles List already contains a Title object with the same name, it always returns false, so I get Title objects with the same name many times in my List. I have debugged this in all the ways I could think of and I couldn't solve it. If i replace token with, let's say token = "TitleName" , then create Title(token), add it in the List and then do the check, it understands that it already exists. I tried the following:

Title titleObj = new Title("titleName");
titles.add(title);
if(titles.contains(titleObj))
    System.out.println("true");

and it does return true. So I guess the cause of the problem is the line

String token = m.group(1);

but i can't find the solution. Could anyone help?

Dim. X
  • 1
  • 3
  • Why not use a `Set` for your collection? – Hovercraft Full Of Eels Mar 21 '20 at 20:54
  • 1
    Problem with this line of code: `return t.getName() == this.getName();` Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Mar 21 '20 at 20:55
  • so, `return name.equals(t.name);` – Hovercraft Full Of Eels Mar 21 '20 at 20:55

0 Answers0