简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM