Reputation: 771
I have the following code:
public ArrayList[] username = new ArrayList[1];
public ArrayList[] password = new ArrayList[1];
public void save(String username, String password){
String uname = userField.getText();
String pword = passField.getText();
username.add(uname);
password.add(pword);
}
I am trying to make an ArrayList
of usernames and passwords (using Window Builder) and add to it when someone wants to create a new user/pass. However I get an error saying "The method add(String) is undefined for the type String."
How do I fix and how do I make it so that the size of my array list can grow as new users are added?
Upvotes: 0
Views: 2081
Reputation: 16
Hope you are using java version compatible with generics(1.5 or more).You should give the type parameter as String like Steve said.
You can also create a user class
public class User{
String uname;
String pwd;
public User(u,p){
uname=u;
pwd=p;
}
}
and create an ArrayList of those user objects in the main class
ArrayList<User> list=new ArrayList<>();
and add those user objects with values retrieved from the fields to the list
list.add(new User(uname,pword))
Upvotes: 0
Reputation: 7728
Why are you maintaining the usernames and passwords in two different lists ?
Your assumption is based that on matching the indexes of both the lists, and then fetching the usernames and passwords for one specific user.
You should avoid doing that. Use a more suited data structure like a map, which maintains a mapping between a key and a value.
public class UsernamePassword
{
private Map<String, String> map = new HashMap<String, String>();
public void save(String username, String password){
String uname = userField.getText();
String pword = passField.getText();
map.put(unmae, pword);
}
}
Upvotes: 2
Reputation: 63064
public ArrayList[] username = new ArrayList[1];
creates an array of ArrayList
. What you want is a an ArrayList of Strings.
public ArrayList<String> usernames = new ArrayList<String>();
It is good practice to "program to the interface", in this case usernames
is a List, whose implementation just happens to be an ArrayList.
public List<String> usernames = new ArrayList<String>();
Upvotes: 2