0

我正在 Eclipse 中处理包含地址和电话号码的联系人管理器项目。添加一个(在本例中为树节点)的方法几乎与另一个相同,只是变量和方法说电话而不是地址。例如 getPhoneIterator() 变为 getAddressIterator()。我正在寻找一种方法来突出显示整个段落并将字母“ADDRESS”一起出现的所有地方更改为字母“PHONE”。

有没有办法做到这一点?

为了说明,这是我的代码;

// Checking if there are addresses, and 
// then checking and adding them one by one to the tree.
if (!currentContact.addressCollectionIsEmpty()){ //If there are addresses...
    addressMainNode = new DefaultMutableTreeNode("Addresses");
    Iterator<Address> addressItr = currentContact.getAddressIterator();
    while(addressItr.hasNext()){
        Address currentAddress = addressItr.next();
        addressSpecificNode = 
            new DefaultMutableTreeNode(currentAddress.toString());
        addressMainNode.add(addressSpecificNode);
    }
    contactNode.add(addressMainNode);
}
4

1 回答 1

1
if (!currentContact.addressCollectionIsEmpty())
{
    addressMainNode = new DefaultMutableTreeNode("Addresses");
    Iterator<Address> addressItr = currentContact.getAddressIterator();
    while(addressItr.hasNext()){
        Address currentAddress = addressItr.next();
        addressSpecificNode = 
            new DefaultMutableTreeNode(currentAddress.toString());
        addressMainNode.add(addressSpecificNode);
    }
    contactNode.add(addressMainNode);
}

上面的代码部分可以移动到一个通用方法中,如下所示:

public <T> addToContactNode(
    boolean isEmpty,
    String treeNodeName,
    Iterator<T> itr) 
{
    if (isEmpty) {
        return;
    }
    mainNode = new DefaultMutableTreeNode(treeNodeName);
    while(itr.hasNext()){
        T current = itr.next();
        specificNode = 
            new DefaultMutableTreeNode(current.toString());
        mainNode.add(addressSpecificNode);
    }
    contactNode.add(mainNode);
}

上面的方法会被调用如下:

// Add addresses.
addToContactNode(
    currentContact.addressCollectionIsEmpty(),
    "Addresses",
    currentContact.getAddressIterator());

// Add Phones.
addToContactNode(
    currentContact.phoneCollectionIsEmpty(),
    "Phones",
    currentContact.getPhoneIterator());
于 2012-12-07T03:11:30.303 回答