Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable defined 2 times in the method

Tags:

java

android

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.

like image 709
Sina Avatar asked Apr 13 '26 20:04

Sina


1 Answers

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);
  }
like image 106
Rajnish suryavanshi Avatar answered Apr 15 '26 10:04

Rajnish suryavanshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!