java - Nullpointer exception when iterating over a list -
i have arraylist of user objects.
private arraylist<user> users; this constructor of class contains array list "users" :
public communicationthread(socket socket, arraylist<user> users) { super("communicationthread"); try { // initialize data fields this.users = users; system.out.println("client connected : " + client_socket.getinetaddress().tostring()); } catch(ioexception e) { system.out.println("could not initialize communication properly. -- communicationthread.\n"); e.printstacktrace(client_out); // inform client. } } i wrote procedure "search_user" searches user given username.
private user search_user(string username) { for(int = 0; < this.users.size(); i++) { user found_user = this.users.get(i); if(found_user.username.equals(username)) return found_user; } return new usernotfound(); } when i'm trying search user gives me nullpointer exception.
exception in thread "communicationthread" java.lang.nullpointerexception @ directoryservice.communicationthread.search_user(communicationthread.java:92) the "users" list empty when i'm searching, should return new "usernotfound" object , not supposed throw nullpointer exception.
looks you're using different constructor create object of communicationthread. instead doing useless null checks , uglyfy code, recommend initialize list when declaring field:
public communicationthread { //updated declaration of users interface list private list<user> users = new arraylist<>(); //rest of code... }
Comments
Post a Comment