0

I have to display the current user into the gui, but it keep saying the the hashset is empty, this has been bugging me for hours. What is the easiest way to fix this? There might be a lot of un used code as i was testing things trying to make it work.

Client.java

public class Client {
    Server.names();
}

Server.java

public class Server {    
    public static HashSet<String> names = new HashSet<String>();

    public static void main(String[] args) throws Exception{                    
        while(true){
            name = in.readLine();
            if(name == null){
                return;
            }
            if(!names.contains(name)){
                 names.add(name);
                 break;
            }            
        }
    }
}
xlm
  • 6,854
  • 14
  • 53
  • 55
  • 1
    Please try to narrow down the amount of code you post here. If the problem is with your HashSet being empty you should show us the portion of code that populates and uses the set. – takendarkk Mar 16 '14 at 04:05
  • i tried to simplify as much as i could, thanks for the help. – user3238481 Mar 16 '14 at 04:32
  • There's no point in checking if a set contains an item before adding it, just add it. Checking if the element is in the set is just as expensive. And since it's a set it's guaranteed to be the same element if it's a duplicate. – aruisdante Mar 16 '14 at 04:34
  • i need to read it in the client class because i have to pass the data into a gui. In other words how can i read the hashset from a different class without creating a new object – user3238481 Mar 16 '14 at 04:40

1 Answers1

1

Your Q is a bit unclear, but if you want to get the HashSet, names from your Server class, you need to get the reference to it by calling Server.name, not Server.name() as it is not a method.

Now names will be empty until you populate it. To populate it you need to call code that will read user input and store it in names. In this case you can call the main method of Server (see this related Q here) but unless you really want that to be your main method of Server, I would recommend renaming the method to populateNames() or something similar.

Community
  • 1
  • 1
xlm
  • 6,854
  • 14
  • 53
  • 55
  • When i use that, the client class reads public static HashSet names = new HashSet() which is empty, and its not reading the names that i added – user3238481 Mar 16 '14 at 15:10
  • @user3238481 please see updated explanation. BTW presumably in your `Server` class, `in` is a `static Scanner` you have declared and initialised? – xlm Mar 16 '14 at 21:34