0

I have an object in java that encodes something as such:

public class Obj(){
    private string[] array = {
        "1","2","3","4",etc...
    };
    public Obj(String param){
        if (param=this.array[1]){ do something.. }
    }
}

So I need to have so info in the background. However, apparently it takes up a lot of RAM. So I was wondering if there is a way to just have the array once for all of those objects instead of having it in every single object.

EDIT:

Made it static. Does the magic. Thank you guys.

Thank you

Goodie123
  • 467
  • 4
  • 16
  • 1
    Ditto on using `static` (and change `this.array` to just `array`, or `Obj.array`). Also, don't compare strings using `==`; use `if (param.equals(array[1]) {...}`, etc. – Ted Hopp Jan 15 '17 at 18:59

3 Answers3

0

You can make it static, then there will be just one array for all objects of the class. Undoubtedly, it would make your program more memory efficient than keeping an array in every object of the class you create.

K.Rzepecka
  • 322
  • 2
  • 9
  • Making it `static` doesn't "keep the array in every object". A `static` array exists independent of any object. – Ted Hopp Jan 15 '17 at 19:04
  • I said that making it static is more efficient than keeping an array in every object. – K.Rzepecka Jan 15 '17 at 19:07
  • Actually, meant to object to the phrase "for all objects of the class". This suggests that the array exists "for" class instances--that is, that it's existence depends on the existence of class instances. (I'm sure you're aware that there is no such dependency and the array exists regardless of whether class instances are created.) Perhaps you meant to say "regardless of how many objects of the class are created" or something like that. – Ted Hopp Jan 15 '17 at 19:40
0

I hope you can make it static:
Static means: that the variable belong to the class, and not to instances of the class. So there is only one value of each static variable, and not n values if you have n instances of the class.

 private static String[] array = {
            "1","2","3","4"...etc
        };
SOP
  • 773
  • 3
  • 9
  • 26
0

You can refactor your array in a separate class that would only contain that array as a final static member, and then you can reuse it in other classes by doing a static access to that member array:

public class MyArray{
     public final static string[] array = { "1","2","3","4",etc...   };
}

public class Obj(){
    public Obj(String param){
        if (param == MyArray.array[1]){ do something.. }
    }
}

Side note

I'm not sure why you would need such an array but if you might want to refactor your code this way:

public class Obj(){

    public Obj(String param){

        //This will check param again string values of 0 ... 100
        for(int i=0; i < 100; i++)
             if (param == String.valueOf(i)){ do something.. }
    }
}
Aria Pahlavan
  • 1,338
  • 2
  • 11
  • 22