0

I am very new in java. I have a class that makes a random array with this code.

public class game {
    private int max = 32;
    private int min = 1;
    private Random r = new Random();
    private Integer[] words_Image = new Integer[10];
    public void setwords_Image(Integer[] words_Image) {
        this.words_Image = words_Image;
        for (int i = 0; i < words_Image.length; i++) {
            int num = r.nextInt(max - min + 1) + min;
            int j = 0;
            while (j < i) {
                if (words_Image[j] == num) {
                    num = r.nextInt(max - min + 1) + min;
                    j = -1;
                }
                j += 1;
            }
            words_Image[i] = num;

        }

    }

    public Integer[] getWords_Image() {
        setwords_Image(words_Image);
        return words_Image;
    }
}

I want to make the array just once, then use the array in entire app while array remains constant. I don't know how to do that because when I make an object from that class this array changed each time. Can anyone help me?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • you just need to know the role of `static` keyword in java. i hope my answer will help you. – Wasi Ahmad Dec 25 '16 at 23:43
  • What you really need is a singleton. @WasiAhmad’s suggestion, static variables, is one way to obtain an effective singleton. There are a couple of others, including an `enum`. Your favourite search engine should be great for finding the options — they surely are described in several places on the Net. – Ole V.V. Dec 26 '16 at 01:22
  • if my answer helped you, you can accept it. (saying this since you are new to stackoverflow) – Wasi Ahmad Dec 26 '16 at 01:24

2 Answers2

1

"because when i make an object from that class this array changed each time" - you need to know about the static keyword in java.

Static Variables: In Java, variables can be declared with the static keyword. An example is given below.

static int y = 0;

When a variable is declared with the keyword static, its called a class variable. All instances share the same copy of the variable. A class variable can be accessed directly with the class, without the need to create a instance.

Without the static keyword, it’s called instance variable, and each instance of the class has its own copy of the variable.

  • It is a variable which belongs to the class and not to object(instance)

  • Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.

  • A single copy to be shared by all instances of the class.

  • A static variable can be accessed directly by the class name and doesn’t need any object

Syntax : <class-name>.<variable-name>

Read the article on Static Methods, Variables, Static Block and Class with Example to know more in detail.

Edit: I wanted you to explore and solve it of your own but since you are struggling, i am adding a solution. Note that, you can achieve what you want in many ways.

class Game {

    private static final int max = 32;
    private static final int min = 1;
    private static final Integer[] words_Image = new Integer[10];

    static {
        setwords_Image();
    }

    private static void setwords_Image() {
        Random r = new Random();
        for (int i = 0; i < words_Image.length; i++) {
            int num = r.nextInt(max - min + 1) + min;
            int j = 0;
            while (j < i) {
                if (words_Image[j] == num) {
                    num = r.nextInt(max - min + 1) + min;
                    j = -1;
                }
                j += 1;
            }
            words_Image[i] = num;
        }
    }

    public Integer[] getWords_Image() {
        return words_Image;
    }
}

public class test {

    public static void main(String[] args) {
        Game g1 = new Game();
        System.out.println(Arrays.toString(g1.getWords_Image()));
        Game g2 = new Game();
        System.out.println(Arrays.toString(g2.getWords_Image()));
    }
}

It outputs: (as you expect)

[1, 32, 18, 20, 27, 8, 9, 31, 3, 19]
[1, 32, 18, 20, 27, 8, 9, 31, 3, 19]
Wasi Ahmad
  • 35,739
  • 32
  • 114
  • 161
  • hi thank for answering. can you be more specific with my example? – Hossein Dehghany Dec 26 '16 at 00:42
  • i want words_image array that contain random numbers made one time then i can use that numbers in my app. when i make my variable static and use myclass.myvariable i get empty array at sratrt – Hossein Dehghany Dec 26 '16 at 00:46
  • I have updated my answer, hopefully it will help you. but i want to encourage you to go through the tutorial and learn everything about `static` in java :) – Wasi Ahmad Dec 26 '16 at 00:58
0

What you really need is a singleton. This is a well known concept in programming, best known from the description in Gamma et al.: Design Patterns, popularly known as the Gang of Four book. You should take a look at the discussions in What is an efficient way to implement a singleton pattern in Java?. The two top answers both advocate an enum for implementing the singleton in Java, while other options are also mentioned in the answers. In your case an enum may look like this:

public enum Game {
    INSTANCE;

    private int max = 32;
    private int min = 1;
    private int size = 10;
    private final int[] wordsImage;

    private Game() {
        wordsImage = new int[size];
        Random r = new Random();
        for (int i = 0; i < wordsImage.length; i++) {
            int num = r.nextInt(max - min + 1) + min;
            int j = 0;
            while (j < i) {
                if (wordsImage[j] == num) {
                    num = r.nextInt(max - min + 1) + min;
                    j = -1;
                }
                j += 1;
            }
            wordsImage[i] = num;
        }
    }

    public int[] getWordsImage() {
        return wordsImage;
    }
}

Classes that need to access the random array do for instance:

    System.out.println(Arrays.toString(Game.INSTANCE.getWordsImage()));

If you want to prevent code that uses the array from putting other numbers in it, return only a copy to callers:

    return Arrays.copyOf(wordsImage, size);
Community
  • 1
  • 1
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
  • If you think that there is any need to make a singleton and that a static variable doesn't suffice, please justify your answer. – Sharcoux Dec 26 '16 at 03:03
  • Each option — static variables and other implementations of singleton — has its pros and cons. You may read more here: [Difference between static class and singleton pattern?](http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern) – Ole V.V. Dec 26 '16 at 12:24
  • I know the difference and in the case of an array of integers, I don't see any pros in making a singleton. Only cons. So, if you believe that a singleton is better in this particular case, please justify your answer. – Sharcoux Dec 26 '16 at 13:32
  • I am not saying one is better than the other in this particular case. I wanted to present the different options, and I am happy to trust the asker to make the pick that suits him or her best. @Sharcoux – Ole V.V. Dec 26 '16 at 13:35