我有2个类图,类地址
+forename
+surename
+street
+houseno
+code
+state
+toString
第二个地址簿
insert(address: Address)
toString()
searchSurename (surename: string): Address[*]
+searchForename(forename: string): Address[*]
我实施了地址:
public class Address {
public static String forename;
public static String surename;
public static String street;
public static int houseno;
public static int code;
public static String state;
public String toString(){
return this.forename + this.surename + this.street + this.houseno + this.code + this.state;
}
如何尽可能简单地实施地址簿?
编辑:
public class addressbook{
private static ArrayList<Address> book;
public addressbook(){
book = new ArrayList<Address>();
}
}
编辑问题:
我是否允许在我们在类图中使用的实现之外的实现中添加新方法或属性?
编辑2:
首先尝试使用ArrayList实现方法searchSurename:
public static String searchSurename(String surename){
boolean exist = false;
if(this.addresses.isEmpty()){
return null;
}
for(int i=0;i<this.addresses.size();i++) {
if(this.addresses.get(i).getSurename() == surename) {
exist=true;
break;
}
if(exist) {
return this.addresses.get(surename);
} else {
return this.addresses.get(surename);
}
}
// return ?!?
}
该程序在任何一行都给出了“this”的错误,也许是一个错误,但我不能告诉你!它看起来有点太难了,我找不到任何实现,搜索列表很简单。
答案 0 :(得分:1)
你可以用这样的方式实现它。查看arrayList的api以使用其方法。
public class Adressbook {
List<Adress> adresses = new ArrayList<Adress>();
public Adressbook(){
adresses = new arraylist<Adress>();
}
public insert (Adress adress){
adresses.add(adress)
}
public searchSurename(String Surename){
}
public searchForename(String forename){
}
public String toString(){
}
ArrayList api: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
答案 1 :(得分:0)
要使用唯一地址,请使用set collection interface
public class Adressbook {
....
private Set<Adress> adresses = null;
public Adressbook(){
adresses = new HashSet<Adress>();
}
public void add(Adress adress){
adresses.add(adress)
}
...
}