I'm making a project for my school and I'm a beginner at ArrayList. Can you explain to me why getUsernamelist() doesn't work?
import java.util.ArrayList;
public class accounts {
//We don't want to create an instance so we used static keyword
static ArrayList Usernamelist;
static ArrayList Passwordlist;
public static void main(String[] args){
Usernamelist = new ArrayList<String>();
Passwordlist = new ArrayList<String>();
Usernamelist.add("admin");
Passwordlist.add("1234");
}
public static Arraylist<String> getUsernamelist(){
return Usernamelist;
}
}
CodePudding user response:
I think its because you are not calling the method getUsernamelist() on the main of the program after you set the values of said ArrayList.
You could try to call a print after you set the values of the ArrayList and call the method getUsernamelist(), like this.
public static void main(String[] args){
Usernamelist = new ArrayList<String>();
Passwordlist = new ArrayList<String>();
Usernamelist.add("admin");
Passwordlist.add("1234");
System.out.print(getUsernamelist());
}
CodePudding user response:
The main method is only invoked to run the class, not to initialize it before another class uses it. So if you have another class that invokes accounts.getUsernamelist() it will get the uninitialized null value.
Here are two possible ways to initialize it:
Within the declaration itself,
static ArrayList Usernamelist = new ArrayList<String>(Arrays.asList(usernameList.add("admin")));
or in a static initializer,
static ArrayList Usernamelist;
static {
Usernamelist = new ArrayList<String>();
usernameList.add("admin");
}
CodePudding user response:
There is no way that this code might works.
You probably wanted to write something like this:
import java.util.ArrayList;
import java.util.List;
public class Accounts {
public static void main(String[] args){
List<String> usernameList = new ArrayList<>();
List<String> passwordList = new ArrayList<>();
usernameList.add("admin");
passwordList.add("1234");
}
}
