Jump to content

[Java] Need help writing an equals() method for a linked list

Xenti3

So the jist of it its, i have a User object that contains a username and a password. The there is a linked list that contains a list of users, i'm trying to compare the user object which holds the entered username and password with the ones in the list. If any of the user's in the list match then it should return true, currently i have a comparison but it doesn't work due to the equals needing an override method. Which i'm stuck on, any ideas? thanks.

 

Current comparison:


public boolean logOnSeller()    {
        Seller tempSeller = new Seller(username, password);
        for (int i = 0; i < userList.size(); i++) {
            if(userList.equals(tempSeller))
            {        
                return true;
            }
        }
        return false;
    }

The problem being i think that the User object is being compared to the memory address of userlist rather than the individual elements in it? Thanks for any help.

PC Specs: i5 4690K, MSI GTX 970 Gaming, 16GB Crucial Ballistx Tactical at 1866Mhz, MSI Guard Pro, 120GB Crucial MX100, 4TB HGST HDD, NZXT H440 Black/Blue

Phone: Oneplus 3 w/ Moto 360 2nd gen

Consoles: New 3DS XL, Xbox One, Nintendo switch soon hopefully.

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, ShrDc said:

Can't you use userList.contains(tempSeller)?

Tried to but it provides the same result as .equals does.

PC Specs: i5 4690K, MSI GTX 970 Gaming, 16GB Crucial Ballistx Tactical at 1866Mhz, MSI Guard Pro, 120GB Crucial MX100, 4TB HGST HDD, NZXT H440 Black/Blue

Phone: Oneplus 3 w/ Moto 360 2nd gen

Consoles: New 3DS XL, Xbox One, Nintendo switch soon hopefully.

Link to comment
Share on other sites

Link to post
Share on other sites

You're trying to compare userList to tempSeller instead of userList item, and you're doing same comparison userList.size()-times. So if there are 100 user on the list, you will compare same thing 100 times. Since it is a linked list it has pretty high complexity to get item on a n-index so getting item from a list by get(index) would be not reasonable, as you do it in sequence, you should use iterator.

 

Other thing, are users unique by username? If so I would think about doing username:string => user:object map, so you could just check if user with that username exists in a map and then check if the password match, it will reduce complexity to be logarithmic. But that depends on if you really need linked list.

Link to comment
Share on other sites

Link to post
Share on other sites

public boolean logOnSeller()    {
        Seller tempSeller = new Seller(username, password);
        for (int i = 0; i < userList.size(); i++) {
            if(userList.get(i).getUsername() == tempSeller.getUsername() && userList.get(i).getPassword() == tempSeller.getPassword())
            {        
                return true;
            }
            else
            {
                return false;
            }
        }
}
Link to comment
Share on other sites

Link to post
Share on other sites

30 minutes ago, ShrDc said:

public boolean logOnSeller()    {
        Seller tempSeller = new Seller(username, password);
        for (int i = 0; i < userList.size(); i++) {
            if(userList.get(i).getUsername() == tempSeller.getUsername() && userList.get(i).getPassword() == tempSeller.getPassword())
            {        
                return true;
            }
            else
            {
                return false;
            }
        }
}

Tried this but it's still returning false even when the data matches.

PC Specs: i5 4690K, MSI GTX 970 Gaming, 16GB Crucial Ballistx Tactical at 1866Mhz, MSI Guard Pro, 120GB Crucial MX100, 4TB HGST HDD, NZXT H440 Black/Blue

Phone: Oneplus 3 w/ Moto 360 2nd gen

Consoles: New 3DS XL, Xbox One, Nintendo switch soon hopefully.

Link to comment
Share on other sites

Link to post
Share on other sites

33 minutes ago, Mr_KoKa said:

You're trying to compare userList to tempSeller instead of userList item, and you're doing same comparison userList.size()-times. So if there are 100 user on the list, you will compare same thing 100 times. Since it is a linked list it has pretty high complexity to get item on a n-index so getting item from a list by get(index) would be not reasonable, as you do it in sequence, you should use iterator.

 

Other thing, are users unique by username? If so I would think about doing username:string => user:object map, so you could just check if user with that username exists in a map and then check if the password match, it will reduce complexity to be logarithmic. But that depends on if you really need linked list.

Yes users are unique by username, the linkedlist isn't a complete requirement but it's the prefered method i was asked for.

PC Specs: i5 4690K, MSI GTX 970 Gaming, 16GB Crucial Ballistx Tactical at 1866Mhz, MSI Guard Pro, 120GB Crucial MX100, 4TB HGST HDD, NZXT H440 Black/Blue

Phone: Oneplus 3 w/ Moto 360 2nd gen

Consoles: New 3DS XL, Xbox One, Nintendo switch soon hopefully.

Link to comment
Share on other sites

Link to post
Share on other sites

  import java.util.*;
  import java.lang.*;
  import java.io.*;

  /* Name of the class has to be "Main" only if the class is public. */
  class User {
    private String username;
    private String password;

    public User(String username, String password){
      this.username = username;
      this.password = password;
    }

    public String getUsername(){
      return this.username;
    }

    public String getPassword(){
      return this.password;
    }

    @Override
    public boolean equals(Object other){
      if(other instanceof User){
        if(other == null || !(other instanceof User)){
          return false;
        }

        if(other == this){
          return true;
        }

        User otherUser = (User)other;

        return (this.username.equals(otherUser.username) && this.password.equals(otherUser.password));
      }

      return false;
    }
  }

  class Main
  {

      public static void main (String[] args) throws java.lang.Exception
      {
        LinkedList<User> users = new LinkedList();

          users.add(new User("A", "abc"));
          users.add(new User("B", "bcd"));
          users.add(new User("C", "cde"));
          users.add(new User("D", "def"));

          User userToCompare1 = new User("C", "cde");
          User userToCompare2 = new User("B", "fgh");

          if(users.contains(userToCompare1)){
            System.out.println("User exists.");
          } else {
            System.out.println("User doesn't exist.");
          }

          if(users.contains(userToCompare2)){
            System.out.println("User exists.");
          } else {
            System.out.println("User doesn't exist or wrong password.");
          }

          //There is a map example if you're curious
          Map<String, User> usersMap = new HashMap();

          ListIterator<User> usersIterator = users.listIterator();
          while(usersIterator.hasNext()){
            User user = usersIterator.next();
            usersMap.put(user.getUsername(), user);
          }

          if(usersMap.containsKey(userToCompare1.getUsername())){
            User user = usersMap.get(userToCompare1.getUsername());
            if(user.getPassword().equals(userToCompare1.getPassword())){ // or user.equals, but name is already equal.
              System.out.println("User exists.");
            } else {
              System.out.println("Wrong password.");
            }
          } else {
            System.out.println("User doesn't exist.");
          }

          if(usersMap.containsKey(userToCompare2.getUsername())){
            User user = usersMap.get(userToCompare2.getUsername());
            if(user.getPassword().equals(userToCompare2.getPassword())){ // or user.equals(userToCompare2), but name is already equal.
              System.out.println("User exists.");
            } else {
              System.out.println("Wrong password.");
            }
          } else {
            System.out.println("User doesn't exist.");
          }
      }
  }

Runnable version: https://repl.it/Gb4v

 

So there is an example how you override equal function of an object, so LinkedList contain will use it.

Link to comment
Share on other sites

Link to post
Share on other sites

it returns false because String is an object and should be compared with equal, other way you compare addresses.

Link to comment
Share on other sites

Link to post
Share on other sites

17 minutes ago, Mr_KoKa said:

  import java.util.*;
  import java.lang.*;
  import java.io.*;

  /* Name of the class has to be "Main" only if the class is public. */
  class User {
    private String username;
    private String password;

    public User(String username, String password){
      this.username = username;
      this.password = password;
    }

    public String getUsername(){
      return this.username;
    }

    public String getPassword(){
      return this.password;
    }

    @Override
    public boolean equals(Object other){
      if(other instanceof User){
        if(other == null || !(other instanceof User)){
          return false;
        }

        if(other == this){
          return true;
        }

        User otherUser = (User)other;

        return (this.username.equals(otherUser.username) && this.password.equals(otherUser.password));
      }

      return false;
    }
  }

  class Main
  {

      public static void main (String[] args) throws java.lang.Exception
      {
        LinkedList<User> users = new LinkedList();

          users.add(new User("A", "abc"));
          users.add(new User("B", "bcd"));
          users.add(new User("C", "cde"));
          users.add(new User("D", "def"));

          User userToCompare1 = new User("C", "cde");
          User userToCompare2 = new User("B", "fgh");

          if(users.contains(userToCompare1)){
            System.out.println("User exists.");
          } else {
            System.out.println("User doesn't exist.");
          }

          if(users.contains(userToCompare2)){
            System.out.println("User exists.");
          } else {
            System.out.println("User doesn't exist or wrong password.");
          }

          //There is a map example if you're curious
          Map<String, User> usersMap = new HashMap();

          ListIterator<User> usersIterator = users.listIterator();
          while(usersIterator.hasNext()){
            User user = usersIterator.next();
            usersMap.put(user.getUsername(), user);
          }

          if(usersMap.containsKey(userToCompare1.getUsername())){
            User user = usersMap.get(userToCompare1.getUsername());
            if(user.getPassword().equals(userToCompare1.getPassword())){ // or user.equals, but name is already equal.
              System.out.println("User exists.");
            } else {
              System.out.println("Wrong password.");
            }
          } else {
            System.out.println("User doesn't exist.");
          }

          if(usersMap.containsKey(userToCompare2.getUsername())){
            User user = usersMap.get(userToCompare2.getUsername());
            if(user.getPassword().equals(userToCompare2.getPassword())){ // or user.equals(userToCompare2), but name is already equal.
              System.out.println("User exists.");
            } else {
              System.out.println("Wrong password.");
            }
          } else {
            System.out.println("User doesn't exist.");
          }
      }
  }

Runnable version: https://repl.it/Gb4v

 

So there is an example how you override equal function of an object, so LinkedList contain will use it.

Thanks alot for your help. That solved the problem perfectly, that was a great explanation.

PC Specs: i5 4690K, MSI GTX 970 Gaming, 16GB Crucial Ballistx Tactical at 1866Mhz, MSI Guard Pro, 120GB Crucial MX100, 4TB HGST HDD, NZXT H440 Black/Blue

Phone: Oneplus 3 w/ Moto 360 2nd gen

Consoles: New 3DS XL, Xbox One, Nintendo switch soon hopefully.

Link to comment
Share on other sites

Link to post
Share on other sites

On 3/24/2017 at 0:00 AM, Mr_KoKa said:

it returns false because String is an object and should be compared with equal, other way you compare addresses.

Right, forgot about that. Used to python now, didn't use java for almost a year.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 3 weeks later...
On 3/23/2017 at 11:11 PM, Xenti3 said:

Thanks alot for your help. That solved the problem perfectly, that was a great explanation.

Can you mark this topic as solved, please?

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×