I want to make an address system, so I have to make an ArrayList for the county and another for the district. Still, the problem is how can I make each element from the first array have an array on its own in the 2nd array? for example if int the 1st array ("Istanbul, bursa") and for 2nd array i want to give Istanbul ("avcilar, fatih") and for bursa i want to give("zaytin, elma")
import java.util.ArrayList;
public class Address {
ArrayList<String> county=new ArrayList();
ArrayList<String> district=new ArrayList();
}
CodePudding user response:
you described a one-to-many relation between country and district. the best way to describe this relation in Java is to have a Country
class with list of districts, and then you can have a list of Country
instances.
public class Country {
ArrayList<String> districts = new ArrayList();
}
public class Address {
ArrayList<Country> countries = new ArrayList();
}
note that by convention, variable names for lists is in plural
now you can create a country. fill its list of districts. repeat for every country and put instances in countries of address
Country turkey = new Country();
turkey.districts.add("Istanbul");
turkey.districts.add("another city");
CodePudding user response:
The data model should be refactored to reflect a hierarchy between "counties" or rather provinces and districts where a county/province has at least a name and a list of related districts. In a simple model a district can be represented with just a name, but generally it may also contain other attributes (e.g., population, area, list of cities/towns/villages, etc.):
public class County {
private String name;
private List<District> districts;
public County(String name, List<District> districts) {
this.name = name;
this.districts = districts;
}
// ... getters
}
public class District {
private String name;
// other details/attributes if needed
public District(String name) {
this.name = name;
}
}
Then assuming there's a method to convert a list of strings representing district names
public static List<District> districts(List<String> names) {
return names.stream().map(District::new).collect(Collectors.toList());
}
The list of counties/provinces may be populated as follows:
List<Country> counties = Arrays.asList(
new County("Istanbul", districts("Adalar", "Avcılar", "Fatih")),
new County("Bursa", districts("Gürsu", "Kestel", "Yıldırım"))
);