javaarraysfor-loopinterfaceinitialization

Is it possible to initialize an array in an interface using a "for" instruction?


Is it possible to initialize an array in an interface using a for instruction?


Solution

  • Simple question - Is it posible to initalize array in an interface?

    Yes.

    This works but i want to initialize array by "for" intsruction. Ok thanks for help

    That's not a simple question ;)

    You can't do this strictly because you can't add a static block to an interface. But you can have a nested class or enum.

    IMHO, that could be more confusing than useful as follows:

    public interface I {
        int[] values = Init.getValue();
    
        enum Init {;
            static int[] getValue() {
                int[] arr = new int[5];
                for(int i=0;i<arr.length;i++)
                    arr[i] = i * i;
                return arr;
            }
        }
    }
    

    Java 8 allows static methods in interfaces, Java 9 also allows private methods, so we can avoid the nested class/enum using such a method:

    public interface I {
        private static int[] getValues() {
            int[] arr = new int[5];
            for(int i=0;i<arr.length;i++)
                arr[i] = i * i;
            return arr;
        }
            
        int[] values = getValues();
    }