Mechamod
Mechamod

Reputation: 31

Use a Object by String?

Is it possible to use a Object if i only got the String? I have an Object 'John' from the Class 'Student'. In the Class 'Student' is a ArrayList 'friends'. I want to access the Object 'John' by using a String (the name of the object). (Line 2 in the example)

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

I hope you understand what i mean (i am sorry for my terrible english :/ )

Upvotes: 0

Views: 66

Answers (3)

yaylitzis
yaylitzis

Reputation: 5534

You have a Student Class and you have created in some point some objects of this class.

Student john = new Student();
Student mike= new Student();
Student mary = new Student();

and you have all these objects stored in an Arraylist allStudents

ArrayList<Student > allStudents= new ArrayList<>();
allStudents.add(john);
allStudents.add(mike);
allStudents.add(mary);

So, if you want to find john from this list you may do:

Option A

If the name for your case is unique and exists also as an attribute in your object, you can iterate the Arraylist and find it:

Student getStudentByName = new Student();
for(Student student : allStudents){
   if(student.getName().equals("john")){ //If name is unique
       getStudentByName = student;
   }
}

Option B

Add all objects in HashMap

Map<String, Student> allStudents= new HashMap<>();
allStudents.put("john", john);
allStudents.put("mike", mike);
allStudents.put("mary", mary);

And then get your desired object by:

Student target = friends.get("john");

Be mind that if you add again :

allStudents.put("john", newStudentObject);

the HashMap will keep the last entry.

Upvotes: 0

Ramazan K&#252;rkan
Ramazan K&#252;rkan

Reputation: 156

You can use map for this problem.

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

Upvotes: 1

Nguyen Tuan Anh
Nguyen Tuan Anh

Reputation: 1036

If I understand correctly, you want to print out name of a student using the variable student. If this is the case, you may want to override the toString() method inside Student class which returns name of that student. For example:

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

    // ... Other methods

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

Then you can do something like this to print out the student name:

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

Upvotes: 0

Related Questions