Variable defined 2 times in the method

Sina :

I was reviewing some methods in the com.google.android.material.tabs.Tablayout when I came along with this method:

private static ColorStateList createColorStateList(int defaultColor, int selectedColor) {
    int[][] states = new int[2][];
    int[] colors = new int[2];
    int i = 0;
    states[i] = SELECTED_STATE_SET;
    colors[i] = selectedColor;
    int i = i + 1;
    states[i] = EMPTY_STATE_SET;
    colors[i] = defaultColor;
    ++i;
    return new ColorStateList(states, colors);
}

How this method could be compiled with variable i being defined 2 times? It is part of the library everyone use.

Rajnish suryavanshi :

Actually it's not like that.

You are checking in Decompiled TabLayout.class file

private static ColorStateList createColorStateList(int defaultColor, int selectedColor) {
        int[][] states = new int[2][];
        int[] colors = new int[2];
        int i = 0;
        states[i] = SELECTED_STATE_SET;
        colors[i] = selectedColor;
        int i = i + 1;
        states[i] = EMPTY_STATE_SET;
        colors[i] = defaultColor;
        ++i;
        return new ColorStateList(states, colors);
    }

But, If you check in Source File TabLayout.java you will get the code as below.

  private static ColorStateList createColorStateList(int defaultColor, int selectedColor) {
    final int[][] states = new int[2][];
    final int[] colors = new int[2];
    int i = 0;

    states[i] = SELECTED_STATE_SET;
    colors[i] = selectedColor;
    i++;

    // Default enabled state
    states[i] = EMPTY_STATE_SET;
    colors[i] = defaultColor;
    i++;

    return new ColorStateList(states, colors);
  }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322492&siteId=1