简体   繁体   中英

How can I store objects from another class in an ArrayList from a different class?

I am quite new to programming. I am creating a project where in class Countries there is data in the form of objects which contain the name of the country and the country's dialing code. There is another class called CountriesList where all the objects from class Country will be stored in an ArrayList. And finally class person where the user will input his country name and phone number and the system will match the country name with the data stored in the array-list and output the dialing code/phone code.

Now the problem is, I can't store the objects from class Countires in the array-list from class CountriesList . Does anyone know how I can store objects from another class in an array list? I tried various ways, but it kept giving errors.

Source code:

public class Countries {

        private String countryname;
        private int phonecode;
        public Countries(String n,int c){
            this.countryname=n;
            this.phonecode=c;
        }
        public String getCountryName(){
            return this.countryname;
        }
        public int getPhoneCode(){
            return this.phonecode;
        }
       public static void main(String[] args){
           Countries usa = new Countries("USA",1);
           Countries india = new Countries("India",91);
           Countries antarctica = new Countries("Afg",677);
           Countries bangladesh = new Countries("Bangladesh",880);
           Countries uk = new Countries("UK",44);
       }
    }
public class CountriesList {
    private Countries list;
    public CountriesList(){
        ArrayList<Countries> list = new ArrayList<>();
    } 
    public static void main(String[] args){

    }
}

Name your class in the singular rather than plural. Each object will represent a single county.

Java conventions for naming variables is camelCase.

More briefly define your country class as a record .

record Country ( String name, int phoneCode ) {}

Just use a List such as ArrayList directly. No need to make a class just to contain a list.

List < Country > countries = new ArrayList<>() ;
countries.add( new Country( "United States , 1 ) ) ;

Use List.of to put all the countries into an unmodifiable list in a single statement.

Search list by the property of name .

String target = "United States" ;
Optional < Country > c = 
    countries
    .stream()
    .filter( country -> country.name.equals( target ) )
    .findAny() 
;

Wrapping your collections (in your case the List) CAN be best-practice, and this is what is then referred to as First Class Collections , but you should only wrap them if you want to add additional behavior (methods) around the collection eg some predefined filter behavior or optional appending based on domain checks.

If you are not planning to create or use additional methods others than the ones the collection API already provides, then you don't need the wrapper and you can simply use the List/Set/Queue whatever that you have.

Btw; you should have written your code like below in order to achieve what you wanted to do, passing the collection via the constructor of the wrapper.

public class CountyList {
    private static final Predicate<Country> disallowPhoneCode999Predicate = (c) -> c.getPhoneCode() != 999;
    private final List<Country> list;
    
    public CountyList(List<Country> countyList){
        this.list = countyList;
    } 

    // delegate methods
    public Country get(int index) {
       return list.get(index);
    }

    // add additional methods (very silly example)
    public void addConditionally(Country country) {
        if (disallowPhoneCode999Predicate.test(country)) {
           list.add(country);
        }
    }

    // or return the wrapped collection (not the best approach design-wise but possible)
    public List<Country> getWrappedCollection() {
       return list;
    }
}

public class Application {
    public static void main(String[] args){
       List<Country> countries = List.of(
                               new Country("USA",1), 
                               new Country("India",91));
       
       CountyList countriesList = new CountyList(countries);
       countriesList.addConditionally(new Country("Bangladesh", 882));
       countriesList.add(new Country("Afg", 677));
      
    }
}

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