我對編程很陌生。我正在創建一個專案,其中在課堂Countries上有包含國家名稱和國家撥號代碼的物件形式的資料。還有一個名為CountriesListCountry 的類的所有物件都將存盤在 ArrayList 中的類。最后person是用戶輸入國家名稱和電話號碼的類,系統會將國家名稱與存盤在陣列串列中的資料進行匹配,并輸出撥號代碼/電話代碼。
現在的問題是,我無法將 class 中的物件存盤在 classCountires的陣列串列中CountriesList。有誰知道我如何將另一個類中的物件存盤在陣列串列中?我嘗試了各種方法,但它一直出錯。
源代碼:
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){
}
}
uj5u.com熱心網友回復:
以單數而不是復數命名您的班級。每個物件將代表一個縣。
Java 命名變數的約定是 camelCase。
更簡單地將您的國家/地區類定義為記錄。
record Country ( String name, int phoneCode ) {}
直接使用List比如ArrayList。不需要僅僅為了包含一個串列而創建一個類。
List < Country > countries = new ArrayList<>() ;
countries.add( new Country( "United States , 1 ) ) ;
用于List.of在單個陳述句中將所有國家/地區放入不可修改的串列中。
按 的屬性搜索串列name。
String target = "United States" ;
Optional < Country > c =
countries
.stream()
.filter( country -> country.name.equals( target ) )
.findAny()
;
uj5u.com熱心網友回復:
包裝你的集合(在你的情況下是串列)可以是最佳實踐,這就是所謂的First Class Collections,但是如果你想在集合周圍添加額外的行為(方法),你應該只包裝它們,例如一些基于域檢查的預定義過濾器行為或可選附加。
如果您不打算創建或使用集合 API 已經提供的方法以外的其他方法,那么您不需要包裝器,您可以簡單地使用您擁有的 List/Set/Queue。
順便提一句; 您應該撰寫如下代碼以實作您想要做的事情,通過包裝器的建構式傳遞集合。
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));
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487493.html
