i'm a girl
i'm a girl

Reputation: 328

Java set variable and method types from one place

I am trying to make a flexible data structure that I can copy paste around. I want it to handle only one data type, but be able to change this easily when copy pasting this around. Consider this simple example:

class Data {
    //customize these
    int a;
    int b;
    int val;
    private int f() {
        return a + b;
    }
    
    //built-in functions that I don't customize
    public void build() {
        int temp = f();
        this.val = temp;
    }
    public int query() {
        return this.val;
    }
}

Suppose I want a and b to be arrays and f to be concatenation. I would have to change the type of a, b, val, f, query, and temp. This would be a pain to change if I have more code that is dependent on the type. I want something like this:

ClassType c = Integer; //or maybe Long, int[], ArrayList ...
c a;
c b;
private c f() {
...

I am not looking for generics. In any particular program, I will have a single fixed type. This is purely to make copy-pasting this data structure around easier, across multiple independent programs. i.e., I do not want to specify these data types on each instantiation (with generics).

Also, ideally, this would not add overhead for int which is a common use case for me (so simply creating a class of whatever data type would not be ideal).

More specifics (kind of unrelated): I want a Segment Tree that I can "customize" to be range min query, sort the range as array, 2D Segment Tree, etc. (note that these 2 cases have different data types, and thus different method signatures) I already have the methods and data types I need figured out, and now I need to implement it.

Upvotes: 1

Views: 101

Answers (1)

Gaurav Jeswani
Gaurav Jeswani

Reputation: 4592

In Java datatype is resolved at compile time, while data value is resolved at runtime. So that is the reason assigning some value as datatype of some variable is not possible in Java.

Upvotes: 1

Related Questions