How do i access ArrayList that is in another class using for each loop

蓝咒 提交于 2020-02-06 07:55:47

问题


How do I use ArrayList in Message() method loop? I want to access the arraylist and get atributes of the person to form final message in registration process.

package sample;

import java.util.ArrayList;

public class PersonRegister {
    private static ArrayList<Person> regiter = new ArrayList<>();

    public void regitration (String name, String email, String phonennr, int year, int monht, int day, int age){
        Person onePerson = new Person(name,email,phonennr, year,monht,day,age);
        regiter.add(onePerson);

    }
}

And this is registration message class

package sample;

public class RegistrationMessage {
    public String Mesage(){

        String out="";

        for(Person onePerson : register){

            out+= onePerson.getName() + " "+ onePerson.getEmail()+ " "+ onePerson.getPhonenr()+ "\n" +
                    " som er fodt: "+ onePerson.getYear()+ "/"+ onePerson.getMonth()+"/"+ onePerson.getDay()+ " er"
                    +onePerson.getAge()+ " år gammel"+"\n";
        }
        return out;
    }
}

回答1:


As mentioned in the comments, your static ArrayList is private. To access it, we must either change its access-modifier to public or create what is called a Getter method.

This code is the latter:

package sample;

import java.util.ArrayList;

public class PersonRegister {
private static ArrayList<Person> regiter = new ArrayList<>();

    public void regitration (String name, String email, String phonennr, int year, int monht, int day, int age){
        Person onePerson = new Person(name,email,phonennr, year,monht,day,age);
        regiter.add(onePerson);

    }

    public ArrayList<Person> getRegiter(){
        return(regiter);
    }
}

The regiter can then be accessed in another class by creating a PersonRegister object and accessing it through dot notation.

PersonRegister personRegister = new PersonRegister();
personRegister.getRegiter(); //returns the ArrayList

I would also say to check some of your spelling; I believe you mean register, month, phonenmr, etc.



来源:https://stackoverflow.com/questions/59867839/how-do-i-access-arraylist-that-is-in-another-class-using-for-each-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!