简体   繁体   中英

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

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;
    }
}

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.

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