简体   繁体   中英

Java : Getter /setter for Arraylist<Object>

so i have :

    ArrayList<data> mi = new ArrayList<data>();

i have a Query which do following :

while (rs.next()) {

            mi.add(new users());
            mi.get(i).name= rs.getString("name");
            mi.get(i).pass= rs.getString("pass");
            }

It works but i want it with Getter/setters like :

mi.get(i).setname( rs.getString("name"));

Edit : Misspelling i had it so

Why cant i call the methode?

采用

mi.get(i).setname(rs.getString("name"));

Your users class should have a public setname(String name) method, which sets the name field of user class

then, mi.get(i).setname(rs.getString("name")); will work

Because it is java. You cannot have such assignment

setname() = rs.getString("name")

It does not make sense. You shall set it as argument:

object.setName(rs.getString("name"))

Also please respect java naming conventions: Class has CamelCase, methods start with lower first character and then continue with camel case as well: setUserName

with

mi.get(i).setname()

you call the method setname() . The result (if any) is not a variable name and you cannot assign a value to it.

If your class has a method setname(String s) then use it as usual in Java:

mi.get(i).setname(rs.getString("name"))

I would recommend using the below approach

while (rs.next()) {
Users user = new Users();
user.setName(rs.getString("name"));
user.setPass(rs.getString("pass"));
mi.add(user);
}

Seems neater to set the values in your object and then adding them to the list.

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