2016-07-03 3 views
0

String 만있는 경우 Object를 사용할 수 있습니까? Class 'Student'의 Object 'John'이 있습니다. 클래스 '학생'에는 ArrayList 'friends'가 있습니다. String (객체의 이름)을 사용하여 Object 'John'에 액세스하려고합니다. (예에서 2 호선) 난 당신이 내가 (내가 내 끔찍한 영어에 대한 미안 : /) 무슨 뜻인지 이해를 바랍니다String을 기준으로 개체를 사용 하시겠습니까?

public void addFriend(Student student, String friend) throws IOException{ 
     student.friends.add(friend); 
     System.out.println("Friend: " + friend + " added to List of " + student); 
    } 

만약 내가 제대로 이해하고

+0

매개 변수로 문자열을 받아들이는 Student 클래스의 생성자를 만들고 싶습니다. 함수 "addFriend"가 학생 객체를 구성하는 것보다 새로 만든 객체를 학생의 친구 목록에 추가하고 Student 클래스의 toString 메서드를 오버로드하여 쉽게 인쇄 할 수있게합니다. –

답변

0

, 당신은 학생의 이름을 인쇄 할 변수 학생을 사용합니다. 이 경우 해당 학생의 이름을 반환하는 Student 클래스 내의 toString() 메서드를 재정의 할 수 있습니다. 예를 들어 :

public class Student { 
    private String firstName; 
    private String lastName; 

    // ... Other methods 

    // here is the toString 
    @Override 
    public String toString() { 
     return firstName + " " + lastName; 
    } 
} 

그런 다음 당신은 학생 이름을 인쇄하기 위해이 같은 작업을 수행 할 수 있습니다

System.out.println("Friend: " + friend + " added to List of " + student.toString()); 
1

은이 문제에 대한지도를 사용할 수 있습니다.

Map<String, Student> friends = new HashMap<String, Student>(); 
friends.put("John", objectOfJohn); 
Student target = friends.get("John"); 
관련 문제