我想将下面的代码从数组转换为任何其他方式(最重要的是有效的),这意味着存在无限的空间,我将不必设置数组的长度。
这怎么办?如何建立无限的城市? 使用LinkedList
我的代码:
public class Country {
//instance variables
private String _countryName; // name of the country
private City[] _cities; // Array of the cities
private int _noOfCities; //number of cities in a country
public void CityArray() {
_cities = new City[MAX_NUM_CITIES];
_noOfCities = 0;
}
//constants:
public final int MAX_NUM_CITIES = 1000;
/**
* Constructer for object in Country class construct Country with info accordingly
* @param countryName represents the name of country
* @param cities represents the cities array
* @param noOfCities represents the number of cities
*/
public Country(String countryName) {
this._countryName = _countryName;
this._noOfCities = _noOfCities;
City[] cities = new City[MAX_NUM_CITIES];
}
boolean addCity(java.lang.String cityName, double XcityCenter, double YcityCenter, double XStationPoint, double YStationPoint, long numOfResidents, int numOfNeighborhoods) {
if (_noOfCities <= MAX_NUM_CITIES) return false;
_cities[_noOfCities++] = new City(cityName, XcityCenter, YcityCenter, XStationPoint, YStationPoint, numOfResidents, numOfNeighborhoods);
return true;
}
public long getNumOfResidents() {
long SumOfCities = 0;
if (_noOfCities > 0) //empty Array
{
SumOfCities = _cities[0].getNumOfResidents();
for (int i = 1; i < _noOfCities; i++)
SumOfCities += _cities[i].getNumOfResidents();
} else
SumOfCities = 0;
return SumOfCities;
}
public String getCountryName() {
return this._countryName;
}
public int getNumOfCities() {
return this._noOfCities;
}
public City[] getCities() {
int noOfCities = this._noOfCities;
City[] cities = new City[noOfCities];
for (int i = 0; i < _noOfCities; i++) cities[i] = new City(this._cities[i]);
return cities;
}
public String toString() {
if (_noOfCities == 0) //empty Array
System.out.println("There are no cities in this country ");
else
for (int i = 0; i < _noOfCities; i++) _cities[i].toString();
return toString();
}
}
答案 0 :(得分:3)
如果长度为:
我建议使用与JDK不同的List
实现之一,特别是http://blog.stevenlevithan.com/archives/javascript-regex-lookbehind和ArrayList
。
第一个使用内部数组,如果添加了一个元素,则可能会对其进行扩展,并且会导致该数组变得太小(它本身全部完成,因此无需担心)。
第二个是节点列表,这意味着对于每个添加的元素,新的(内部)节点对象将附加到最后一个节点。
您当然必须为此更改代码。
_cities
定义为List<City>
:private List<City> _cities
_cities = new ArrayList<>();
或_cities = new LinkedList<>();
_cities.add(new City(cityName, XcityCenter, YcityCenter, XStationPoint, YStationPoint, numOfResidents, numOfNeighborhoods));
在您的getNumOfResidents
中,您可以使用以下代码段(该代码段使用Java 8中引入的Java流API):
return _cities.stream()
.mapToLong(City::getNumOfResidents)
.sum();
对于getCities()
,您必须将返回类型更改为List<City>
并使用以下命令:return new ArrayList<>(_cities)
或return new LinkedList<>(_cities)
取决于您要实现的实现使用。