How to avoid using the same Array in 2 different classes?

1

This question arose when creating multiple classes and having to create the same array several times in these classes:

private final static String[] types = { String.class.getSimpleName(), Integer.class.getSimpleName(),
            Date.class.getSimpleName(), Boolean.class.getSimpleName() };

This Array contains the values: "String", "Int", "Date", "Boolean" , the goal of the array is to contain the items of a JComboBox which will be used in example these 2 classes:

Class 1:

public class Clase1 extends JPanel {

private final static String[] types = { String.class.getSimpleName(), Integer.class.getSimpleName(),
                Date.class.getSimpleName(), Boolean.class.getSimpleName() };

JComboBox box = new JComboBox(types);
//codigo
}

Class2:

 public class Clase2 extends JPanel {

        private final static String[] types = { String.class.getSimpleName(), Integer.class.getSimpleName(),
                        Date.class.getSimpleName(), Boolean.class.getSimpleName() };

        JComboBox box = new JComboBox(types);
        //codigo
        }

How can I avoid creating / repeating the creation of this object in multiple classes, are there any Best Practices for this?

    
asked by Bryan Romero 14.11.2018 в 04:36
source

1 answer

2

Declare the static array in a class and then call it from the classes you need without changing it.

public class ArrayGlobal{

  public static String[] types = { String.class.getSimpleName(), Integer.class.getSimpleName(),
            Date.class.getSimpleName(), Boolean.class.getSimpleName() };
}

Then in your classes you agree with

import static ArrayGlobal.*;

 public class Clase2 extends JPanel {

      //Obtener el primer elemento
       types[0]; 

        JComboBox box = new JComboBox(types);
        //codigo
        }

Another way

public class Clase2 extends JPanel {

          //Obtener el primer elemento
           ArrayGlobal.types[0]; 

            JComboBox box = new JComboBox(ArrayGlobal.types);
            //codigo
            }
    
answered by 14.11.2018 / 06:49
source