一个糟糕的版本:
public class ExchangeRates {
private String name;
private String[] names;
private float[] rates;
public ExchangeRates( String name ) {
this.name = name;
this.names = {};
this.rates = {};
}
public int amountOfRates() {
return rates.length;
}
public float averageRate() {
float sum = 0;
for ( float rate : rates )
sum += rate;
return sum / rates.length;
}
public float getRate( String name ) {
for ( int i = names.length - 1; i >= 0; i -- )
if ( names[ i ].equals( name ) )
return rates[ i ];
return 0;
}
public void setRate( String name, float rate ) {
for ( int i = names.length - 1; i >= 0; i -- )
if ( names[ i ].equals( name ) ) {
rates[ i ] = rate;
return;
}
names = Array.copyOf( names, names.length + 1 );
rates = Array.copyOf( rates, rates.length + 1 );
names[ names.length - 1 ] = name;
rates[ rates.length - 1 ] = rate;
}
}
第二个坏版本(更好一点。OOP):
public class ExchangeRates {
private static class Rate {
private String name;
private float rate;
Rate( String name, float rate ) {
this.name = name;
this.rate = rate;
}
}
private String name;
private Rate[] rates;
public ExchangeRates( String name ) {
this.name = name;
this.rates = {};
}
public int amountOfRates() {
return rates.length;
}
public float averageRate() {
float sum = 0;
for ( Rate rate : rates )
sum += rate.rate;
return sum / rates.length;
}
public float getRate( String name ) {
for ( Rate rate : rates )
if ( rate.name.equals( name ) )
return rate.rate;
return 0;
}
public void setRate( String name, float rate ) {
for ( Rate rate : rates )
if ( rate.name.equals( name ) ) {
rate.rate = rate;
return;
}
rates = Array.copyOf( rates, rates.length + 1 );
rates[ rates.length - 1 ] = new Rate( name, rate );
}
}
你真的应该使用地图。
public class ExchangeRates {
private String name;
private Map<String,Float> rates;
public ExchangeRates( String name ) {
this.name = name;
this.rates = new HashMap<String,Float>();
}
public int amountOfRates() {
return rates.size();
}
public float averageRate() {
float sum = 0;
for ( Float rate : rates.values() )
sum += rate;
return sum / rates.size();
}
public float getRate( String name ) {
Float rate = rates.get( name );
return rate == null ? 0 : rate.floatValue();
}
public void setRate( String name, float rate ) {
rates.put( name, rate );
}
}