增强java代码以提高效率

时间:2017-01-10 10:12:53

标签: java gwt

我正在尝试使用selenium扩展GWT树,并且我成功地使用了该代码

for (int i = 0; i < elem.size(); i++) {
 if (!elem.get(i).isExpanded() || !elem.get(i).isLeaf()) {
  elem.get(i).toggleExpand();
 }
 for (int j = 0; j < elem.get(i).getChildren().size(); j++) {
  if (!elem.get(i).getChildren().get(j).isExpanded() || 
                        !elem.get(i).getChildren().get(j).isLeaf()) {
   elem.get(i).getChildren().get(j).toggleExpand();
  }
  for (int k = 0; k < elem.get(i).getChildren().get(j).getChildren().size(); k++) {
   if (!elem.get(i).getChildren().get(j).getChildren().get(k).isExpanded() ||
              !elem.get(i).getChildren().get(j).getChildren().get(k).isLeaf()) {
    elem.get(i).getChildren().get(j).getChildren().get(k).toggleExpand();
   }.....
  }
 }
}

我的问题是如何增强代码或如何放入递归方法?

3 个答案:

答案 0 :(得分:1)

为了使代码更具可读性,您可以做一些事情(:

重用方法结果,例如batchInputDStream.map(new Function<Tuple2<String,String>, FreshBatchInput>() { @Override public String call(Tuple2<String, String> arg0) throws Exception { StringReader reader = new StringReader(arg0._2); JAXBContext jaxbContext = JAXBContext.newInstance(FreshBatchInput.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); FreshBatchInput input = (FreshBatchInput)jaxbUnmarshaller.unmarshal(reader); return input.getPath(); } }); 的那个或使用扩展的for循环(如果elem.get(i)等支持那个):

elem

此外,由于您似乎对元素及其子元素执行相同操作,因此您可以提供一种方法,例如:

for (int i = 0; i < elem.size(); i++) {
  ElementClass element = elem.get(i);
  if (!element.isExpanded() || !element.isLeaf()) {
    element.toggleExpand();
  }

  ...
}

然后你的循环看起来像这样:

public void expandIfNeeded(ElementClass element) {
  if (!element.isExpanded() || !element.isLeaf()) {
    element.toggleExpand();
  }
}

此外,如果您不需要索引for (int i = 0; i < elem.size(); i++) { ElementClass element = elem.get(i); expandIfNeeded( element ); ... //handle children here and call the same method for those (could also be using recursion) } i是可迭代的,您可以使用扩展名:

elem

当然递归会使它更具可读性,特别是如果你不知道树的深度:

for ( ElementClass element : elem ) {
  expandIfNeeded( element );

  ... //handle children here and call the same method for those (could also be using recursion)
}

答案 1 :(得分:0)

无法读取的代码。

尝试这样的事情:

for (int i = 0; i < elem.size(); i++) {
  if (!elem.get(i).isExpanded()) {
    elem.get(i).toggleExpand();
  }
  // I don't know what this method returns; no time to research for you
  List<Element> children = elem.get(i).getChildren();
  for (int j = 0; j < children.size(); j++) {
      // don't know what you call it; must be a void method of some kind
      yourMethodName(children.get(i));
  }
}

答案 2 :(得分:0)

您可以使用以下代码递归切换元素。

public static void toggleElement(Element elem){

        if(elem.isExpand() || elem.isLeaf()){
            return;
        }else{
            elem.toggledExpand();
        }
        List<Element> children=elem.getChildren();
        for (int i = 0; i < children.size(); i++) {
            toggleElement(children.get(i));
        }
    }

希望它能解决您的问题。