因此,我尝试使用枚举数据类型作为参数来代替传入的对象。我知道一个简单的 switch 语句可以工作,但这对我来说似乎并不优雅。我已经搜索并发现枚举也可以附加操作,但我不太清楚在这种情况下如何使用它,或者是否有可能,或者我是否真的很累。让我尝试使用代码来解释我在问什么。
首先,我有一个类,其中包含其他对象的某些字段,我基本上试图使用枚举来引用。在这种情况下,我有一个作用于树的一个字段的方法,因为它们是多棵树,该方法需要知道要作用于哪棵树。
public class bstContactManage()
{
// fields of other objects
BST searchTreeFirstName = new BST(new ComparatorObjOne);
BST searchTreeLastName = new BST(new ComparatorObjTwo);
// and so on and so forth
public boolean modify(Contact contactToFind, BST ToFindIn, String newContactInfo)
{
Contact contUpdate = new Contact(ContactToFind)//save for readdition to tree
contUpdate.update(newContactInfo);
toFindIn.remove(contactToFind);
if(toFindIn.add(contUpdate)) return true;
else return false;
}
}
我想知道或或多或少思考的是如何用我知道我可以使用 switch 语句的枚举替换 BST 参数,但这似乎并不比传递一个 int 值并让它更优雅可能更有效去野外!
那么有没有办法让方法看起来像
public boolean modify(Contact contactToFind, Enum BSTType, String newContactInfo)
{
Contact contUpdate = new Contact(ContactToFind)//save for readdition to tree
contUpdate.update(newContactInfo);
BSTType.remove(contactToFind);
if(BSTType.add(contUpdate)) return true;
else return false;
}
我的大部分问题都源于这样一个事实,例如
bstContactManage man = new bstContactManage()
将在另一个类中实例化,因此这样做不安全或对我来说似乎不合适
man.modify(contactIn, man.searchTreeFirstName, "String");
更新:
所以为了更清楚,我有另一种方法 find 搜索给定的 BST,目前我正在像这样实现它
public List<Contact> find(BinarySearchTree treeUsed, String findThis)
{
//create a new contact with all fields being the same, find is dependent and comparator on tree;
Contact tempContact = new Contact(findThis, findThis, findThis);
return treeUsed.getEntry(tempContact); // where getEntry returns a list of all matching contacts
}
我可以做类似的事情
public List<Contact> find(EnumField field, String findThis)
{
BST treeUsed;
switch(Field){
case FIRST:
treeUsed = this.searchTreeFirstName;
break;
cast LAST:
treeUsed = this.searchTreeLastName;
break;
Contact tempContact = new Contact(findThis, findThis, findThis);
return treeUsed.getEntry(tempContact); // where getEntry returns a list of all matching contacts
}