I've two different classes:
Cliente.java
public class Cliente {
private static String user;
private static String password;
public Cliente (String usr, String pass) {
user = usr;
password = pass;
}
public String getUser() {
return user;
}
}
And AddToArrayList.java, where I create a Client type ArrayList and and some clients:
public class AddToArrayList{
static ArrayList<Cliente> listaClientes = new ArrayList<Cliente>();
public static void main(String[] args) throws IOException {
Cliente c1 = new Cliente("pepe","pepe1");
Cliente c2 = new Cliente("jose","jose1");
Cliente c3 = new Cliente("edu","edu1");
listaClientes.add(c1);
listaClientes.add(c2);
listaClientes.add(c3);
printArraList();
}
public static void printArraList() throws IOException {
for (Cliente c : listaClientes) {
System.out.println(c.getUser());
}
}
}
Why does this funciont prints me:
edu
edu
edu
Instead of:
pepe
jose
edu
Thanks in advance.
-
+1 for mentioning "super simple problem", in the title.Adeel Ansari– Adeel Ansari2011年06月09日 07:31:42 +00:00Commented Jun 9, 2011 at 7:31
5 Answers 5
Because you've made the variable user in your class Cliente static. If you remove the static keyword everything should work as you want.
A static variable is shared across all instances of the class.
The following site has a good reference on the static keyword, I suggest you read it :).
Comments
Static variables are Class level variables. To have separate copies of String user; and String password; for each instance of Cliente, make then non-static.
Comments
The following are static, which means that they're shared by all instances of the class:
private static String user;
private static String password;
Remove the static modifiers, and each instance will get its own user and password.
Comments
You've declared the fields in Cliente static. So the fields keep the last value that you've set: and thats user edu.
Change it to:
private String user;
private String password;
Comments
Remove the static modifier, as it is used if there is a need for a variable to be common to all the objects of a single java class. An instance is not a must to modify the static variable, which is not required in case of user and password in your case.