클래스 사용자 {자바에서 목록 클래스 변수를 가져 오는 방법은 무엇입니까?
문자열 이름; int age}}
목록 listuser = new arrayList();
abouve 코드에서 listuser를 사용하여 클래스 구성원 변수 이름과 나이에 액세스하는 방법 ?? 도와주세요, 미리 감사드립니다.
클래스 사용자 {자바에서 목록 클래스 변수를 가져 오는 방법은 무엇입니까?
문자열 이름; int age}}
목록 listuser = new arrayList();
abouve 코드에서 listuser를 사용하여 클래스 구성원 변수 이름과 나이에 액세스하는 방법 ?? 도와주세요, 미리 감사드립니다.
글쎄, 먼저 사용자 클래스의 이름과 나이 필드에 대한 몇 가지 getter를 만들어야합니다.
class User{
String name; int age; //these are private by default so you cannot access them
//create getters for the 2 members in order to access them outside of the User class
public string getName()
{
return name;
}
public int getAge()
{
return age;
}
}
다음 예를 들어, 당신은 이미 당신이 할 수있는 배열 목록에 사용자를 추가 한 가정 : - 목록 < E>는주의해야한다
User user = (User)listuser.get(position); //cast the object at "position" to user.
string name = user.getName();
한가지 더 그 목록 것은 제네릭 형식 등이다
목록이 유형의 목록임을 지정해야합니다. 귀하의 경우 사용자 유형 목록입니다. 나는 기본 액세스와 변수를 사용하고 위에 다시
public class User {
String name;
int age;
User(String nm, int age) {
name = nm;
this.age = age;
}
public static void main(String args[]) {
List<User> listuser = new ArrayList<User>();
listuser.add(new User("Foo", 21));
listuser.add(new User("Bar", 22));
System.out.println(listuser.get(0).name + " : " + listuser.get(0).age);
System.out.println(listuser.get(1).name + " : " + listuser.get(1).age);
}
}
: 데모를 들어
, 여기 당신이 목록을 사용하는 방법입니다. 일반적으로 사설 액세스로 변수를 유지해야하므로 Dan Dinu와 마찬가지로 getter 및 setter를 지정하고 해당 변수에 액세스해야합니다.