2013-06-27 11 views
2

그래서 전달되는 개체 대신 매개 변수로 열거 형 데이터 형식을 사용하려고합니다. 간단한 switch 문이 작동하지만 실제로는 나에게 우아하지는 않습니다. . 나는 수색하고 발견 한 enums는 또한 그들에 붙어있는 행동을 할 수 있지만, 나는이 경우에 그것을 사용하는 방법이 분명하지 않거나 심지어 그것이 가능하다면, 아니면 내가 정말로 피곤하다면. 내가 묻고있는 것을 설명하기 위해 코드를 사용하도록하겠습니다.enum을 매개 변수로 사용하기

먼저 다른 개체의 특정 필드가있는 클래스를 사용하여 기본적으로 열거 형을 참조하려고합니다. 이 경우에는 트리의 필드 중 하나에서 작동하는 메서드가 있습니다. 그 이유는 트리가 작동 할 트리를 알 필요가있는 여러 트리가 있기 때문입니다.

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 
} 
+0

이름 또는 성으로 인덱싱 연락 생각 이진 검색 트리를 의미합니다.)'enum'이 될까요? –

+0

이 경우 열거 형으로 만들려고하지 않고 있습니다. 특정 개체를 클래스의 필드로 참조 할 수있는 열거 형을 갖기 위해 노력하고 있습니다.다른 클래스에서 modify()를 호출한다는 사실을 기반으로합니다. 나는 다음에 if (1) toFindIn = suchandsuchtree와 같은 체크를 실행하는 int 필드를 수정할 수 있습니다. 또는 열거를 가지고 스위치 문을 만들 수 있지만 더 이상 나에게 논리적 인 것, 나는 enums의 고급 사용을 찾았습니다. 뭔가 실종 된 것처럼 느껴집니다. – chadvonburgess

답변

2

열거 형은 해당 메서드의 다른 구현을 제공 할 수 있습니다.

enum Op { 
    PLUS { 
     int exec(int l, int r) { return l + r; } 
    }, 
    MINUS { 
     int exec(int l, int r) { return l - r; } 
    }; 
    abstract int exec(int l, int r); 
} 

가 그럼 난 5 플러스

7 열거를 사용하는 방법에 대한보다 자세한 사항은 http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html를 참조 수행 할 Op.PLUS.exec(5, 7)을 할 수있는 : 좋은 예는 수학 연산 될 것입니다.

당신의 경우에는 논리 및 상태가 많은 항목에 대해 열거 형을 사용하지 않지만 다른 구현 방식을 가진 열거 형을 사용하는 방법은 여기에 나와 있습니다. 변수 이름과 클래스 이름을보고

enum BSTType { 
    SearchTreeFirstName { 
     void someMethod(Contact c) {...} 
    }, 
    SearchTreeLastName { 
     void someMethod(Contact c) {...} 
    }; 
    abstract void somemethod(Contact c); 
} 

public boolean modify(Contact contactToFind, BSTType bstType, String newContactInfo) { 
    // ... 
    bstType.someMethod(contact); 
    // ... 
} 

, 나는 당신이 실제로 의미하는 것은 TreeSet의에서 중 왜`BST` (가정한다

enum IndexType implements Comparator<Contact> { 
    IndexByFirstName { 
     @Override 
     public int compare(Contact o1, Contact o2) { 
      return o1.firstName.compareTo(o2.firstName); 
     } 
    }, 
    IndexByLastName { 
     @Override 
     public int compare(Contact o1, Contact o2) { 
      return o1.lastName.compareTo(o2.lastName); 
     } 
    }; 
} 
TreeSet<Contact> contacts = new TreeSet<Contact>(IndexType.IndexByLastName); 
+1

몇 가지 설명이 도움이 될 것입니다. [답변]을 참조하십시오? – mtk

+0

또한 TreeSet이 동일한 성으로 연락처를 덮어 쓰지 않게하려면 먼저 성으로 정렬 된 비교기를 만드는 데 유용한 구아바의 'Ordering.compound'를 찾은 다음 고유 한 ID로 –

+0

귀하의 대답은 매우 유용했습니다. exec 메서드를 사용하여 트리에 대한 참조를 반환하려고했지만 예상 한 정적 문제가 발생했습니다. 이제는 switch 문을 사용합니다. – chadvonburgess

관련 문제