简体   繁体   中英

How to acess an ArrayList from an Object inside a HashMap? JAVA

I've stored an object with some variables and an ArrayList in a HashMap, and I'd like to know how I can add or remove elements from that list.

    class Person{
        String name;
        int age;
        ArrayList<String> amigos = new ArrayList<>();

        public Person(String name, int age){
           this.name = name;
           this.age = age;
           amigos.add("Ana");
           amigos.add("Pedro");}
        }

    public class TestMap {
        public static void main(String[] args){
            Map<String, Person> mapa = new HashMap<>();
            mapa.put("João", new Person("João", 24));
        }
    }

I'd like to add another person, John, for example to that list, but I don't know how to access that list.

It was explicitly asked for me to store the objects in a HashMap, so that cannot be changed.

You should declare the variables private and access them via getters/setters.

class Person {
    private String name;
    private int age;
    private List<String> amigos = new ArrayList<>();

    public ArrayList<String> getAmigos () {
        return amigos;
    }

    public void addAmigo(String amigo) {
        amigos.add(amigo);
   }
}

And to access the Person in the map use the key

mapa.get("João").addAmigo("amigoName");

You should also consider make amigos List<Person> instead of List<String> , depends on your use case.

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