所以,我想使用一个枚举的数据类型作为传入的对象的地方参数。我知道一个简单的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;
}
}
什么我不知道或多或少玩味的是如何与更换BST参数枚举 我知道我可以使用switch语句,但似乎没有任何更有效的也许不只优雅传递一个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人=新bstContactManage()
将在另一个类中实例化,因此它是不安全的或似乎不适合做类似 man.modify(contactIn, man.searchTreeFirstName, "String");
更新:
使更多的澄清,我有另一种方法找到该搜索一个给定的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
}
为什么'BST'(假设索引联系代表二进制搜索树)是一个'enum'? –
在这种情况下,我不想让它枚举,即时只是试图有一个枚举类型,可以引用特定对象作为类中的字段。基于这样一个事实,即从不同的类调用modify()。我可以有一个int字段在修改,然后通过检查运行,说如果(1)toFindIn = suchandsuchtree;或者我可以拿枚举并创建一个switch语句,但这对我来说看起来不再符合逻辑,我查阅了更高级的枚举的使用,并且我觉得像是有一些即将丢失的东西 – chadvonburgess