有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java哪个更高效

这是我为分配一组连续按钮而想到的。我喜欢这种风格,但是使用“按id查找”来执行单个按钮会更有效吗

    for(int i = 0; i < NanoConstants.NUMBER_OF_BUTTONS;i++){ //assign buttons
        Button addButton = (Button) findViewById(getResources().getIdentifier("project_button_" + String.valueOf(i), "id", getPackageName()));
        addButton.setText(getResources().getStringArray(R.array.project_names)[i]);
        addButton.setOnClickListener(this);
        mProjectButtons.add(addButton);
    }

谢谢大家


共 (3) 个答案

  1. # 1 楼答案

    不,不会的for循环与展开的版本一样高效,可读性更好,并减少代码和复杂性

  2. # 2 楼答案

    由于这段代码在应用程序启动时似乎只运行一次,我将避免尝试对其进行微优化。坚持让代码最具可读性的风格

  3. # 3 楼答案

    您可以在groupview中添加按钮,并使用getChildAt循环其childs 并检查视图是否为按钮,如下图所示:

    int childCnt = viewGroup.getChildCount();
    for(int i=0;i<childCnt;i++){
      View view = viewGroup.getChildAt(i);
      if(view instanceof Button){
        Button button = (Button)view;
        addButton.setText(getResources().getStringArray(R.array.project_names)[i]);
        addButton.setOnClickListener(this);
        mProjectButtons.add(addButton);
      }
    }
    

    即使现在添加了一个按钮,也无需更改此代码,只需将其添加到布局中,并在数组中添加一个值即可。
    但正如埃利奥特·弗里希所说:

    Since this code appears to run once on application start-up I would avoid trying to micro-optimize it. Stick with the style that makes the code the most readable.