开发者

Super simple problem with ArrayList in Java

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:

开发者_如何学Pythonpepe

jose

edu

Thanks in advance.


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 :).


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.


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.


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;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜