Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Best way to store and access a list of objects

What i want to do is store some instances of my class on a list and get a specific instance from that list.

This is an example of a custom class

public class Person
{
    private String name;
    //Several unrelevant fields here

    public Person(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return name;
    }

    //Several unrelevant methods here
}

And this is the code i'm currently using to get one of the instances on the list, that is on the main class.

public class Main
{
    private List<Person> people = new ArrayList<Person>();
    //More unrelevant fields here

    public Person getPerson(String name)
    {
        for (Person p : people)
            if (p.getName().equalsIgnoreCase(name))
                return p;
        return null;
    }
    //More unrelevant methods here
}

My question is if there's any other way to write this to increase the performance.

like image 405
user2605421 Avatar asked Sep 26 '13 19:09

user2605421


1 Answers

Use a Map whose keys are the names and whose values are the people.

like image 171
Eric Stein Avatar answered Sep 24 '22 01:09

Eric Stein