2014-03-24 31 views
0

好吧,我想查找一个查找某些对象(在我的情况4中)的algorythm,并找到具有最小成员变量的对象。假设你可以通过object.getIntegerValue()查找带有最小成员变量的对象

在我的情况下,我有4个android布局,并希望找到最小的孩子的布局。

我认为会有很多解决方案,但我只想找到一个快速的解决方案。不管有多脏等等....

到目前为止我的代码是短暂的,肮脏和总不返回与最小的成员变量的对象,但只有在这里作为一个代码示例:

private LinearLayout layoutChanger(){ 
    int one, two, three; 
    one = layoutOne.getChildCount(); 
    if ((two = layoutTwo.getChildCount()) <= one) { 
     if ((three = layoutThree.getChildCount()) <= two) { 
      if ((layoutFour.getChildCount()) <= three) 
       return layoutFour; 
      return layoutThree; 
     } 
     return layoutTwo; 
    } 
    return layoutOne; 
} 

编辑: 我知道如何做到这一点我比较想获得关于如何加快东西建议...

媲美真快呢?或者我应该清楚自己的OOP解决方案以获得更好的性能?

+3

实施[可比较](http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html)? – Mena

+0

你的代码有几个问题。如果'three'是最小的,那么只要'two'''''''',你的方法就永远不会表示。相反,它会返回'two'的值,并且永远不会测试'three'的值。 – mttdbrd

回答

0
private LinearLayout layoutToggler(LinearLayout[] layoutArr){ 
     int currentChildCount; 
     int minChildCount = MAX_VAL; 
     LinearLayout retLayout = null; 
     for(LinearLayout layout:layoutArr){ 
      if((currentChildCount = layout.getChildCount()) == MIN_VAL){ 
       retLayout = layout; 
       break; 
      } 
      else if(currentChildCount < minChildCount) { 
       retLayout = layout; 
       minChildCount = currentChildCount; 
      } 
     } 
     return retLayout; 
    } 

感谢阿灵顿s因此,这是他的想法带到一个工作的解决方案。

3

只是一个例子:

int childCount; 
    Layout[] myLayouts = {layoutOne,layoutTwo,layoutThree}; 
    Layout selected; 
    for(Layout layout:myLayouts){ 
     if(childCount=0 || childCound>layout.getChildCount()) { 
      selected = layout; 
      childCount = layout.getChildCount(); 
     } 
    } 
    return layout; 
+0

我不喜欢创建数组myLayouts。您可以创建一个由getChildCount()填充的int数组。它会比创建一个数组更有效的内存,只是为了遍历它们。 – mttdbrd

+0

我认为最好的方法是将其转换为一个方法,该方法将接收一个不确定的对象数组,如getMinLayout(Layout ... layouts) – GhostDerfel

1

以下是 Java代码,这只是(Java等)的伪代码给予OP的想法...

lowestPossibleValue = ?; 
currentLowestValue = MAX; 
foreach (object : collection) { 
    if (object.getValue == lowestPossibleValue) { 
     foundObject = object; 
     break; 
    } else { 
     if (object.getValue < currentLowestValue) { 
      foundObject = object; 
     } 
    } 
} 

// foundObject包含您的结果

+0

Tha答案在这里也是正确的,但这不是Java – GhostDerfel

+0

@GhostDerfel I从来没有建议它是Java,这个解决方案太明显了,在这种情况下,我宁愿避免“给codez”,因此提问者将有机会至少想一点 –

+0

我认为你误解了我的问题,因为我没有尝试找到一个明显的解决方案,但速度很快。 –

相关问题