Home > Net >  Easiest way to generate an array of constants in java
Easiest way to generate an array of constants in java

Time:10-08

So basically I'm making an application in which I need to have a constant array of my class Note. For sake of code readability, I'd ideally generate the 108 note values for the array (octaves 0-8, 12 notes an octave) at runtime rather than having it hardcoded. This is how I'm trying to do it currently:

public class Note{
   ...

   public static class Constants{

        public static final int lowestOctave=0;
        public static final int highestOctave=8;
        public static final int numOfOctaves=highestOctave 1;
        public static final int numOfNotes=numOfOctaves*12;

        private static Note[]allNotesArray=new Note[numOfNotes];
        {
          for(int i=0; i<numOfNotes; i  ){
             allNotesArray[i]=new Note(/*Note params*/);
          {
        }
   }
}

Currently this results in an array full of nulls. I have populated arrays in the same way in final classes, but not sure how to go about doing it for static classes. I know when you create a static/static final array the array itself and the array length are unchangable, but the elements inside the array are changable. As such, I can populate the allNotesArray in the main Note class, but this defeats the purpose of having a constants class. If anyone has any ideas on how to get it working this way that would be great, equally if anyone has any better methods on how to create the array as a constant that would be great too!

CodePudding user response:

You could use an immutable list--see https://www.baeldung.com/java-immutable-list for instance.

You could also write a little script to generate the source code, and then copy that in. This might actually be better than an immutable list, because then you don't have to worry about runtime errors, and you can get all the nice code completion stuff in your IDE.

CodePudding user response:

import java.util.Arrays;

You can use above class with fill() method like this

Arrays.fill(allNotesArray,new Note());

Or You can use Arrays.setAll() also.

  • Related