Olgidos
Olgidos

Reputation: 231

Java set generic Value of an Object in an ArrayList

I have a class

 public class ValueObject<T> {
        private T value;

        public void setValue(T value){
          this.value = value
        }
    }

In another class I have an Array of the Objects from the first Class

ArrayList<ValueObject<?>> valueObjects = new ArrayList<>();
ArrayList<String> valueNames = new ArrayList<>();

now I want to write a Method which looks in a second array for a name and assigns a new value to an instance of the first object in that arrayList

ValueObject<?> get(String name) {
        return valueObjects.get(valueNames.indexOf(name));
}

public <T> void set(String name, T value) {
     get(name).setValue(value);
}

But I don't get this to work. Do I need to write something with ? in the set() Method?

Thanks

Upvotes: 0

Views: 1422

Answers (1)

tkruse
tkruse

Reputation: 10685

You don't provide a full example, so not sure which will help you.

Version 1 if you can use List<ValueObject<T>> because all ValueObjects hold the same type.

static class Lookup<T2> {

    List<ValueObject<T2>> valueObjects = new ArrayList<>();
    List<String> valueNames = new ArrayList<>();

    ValueObject<T2> get(String name) {
        return valueObjects.get(valueNames.indexOf(name));
    }

    public void set(String name, T2 value) {
        get(name).setValue(value);
    }
}

Version 2 if valueObjects really contains ValueObject with different contained classes:

@SuppressWarnings("unchecked")
static class Lookup2 {

    List<ValueObject<?>> valueObjects = new ArrayList<>();
    List<String> valueNames = new ArrayList<>();

    /* unsafe get */
    ValueObject<?> get(String name) {
        return valueObjects.get(valueNames.indexOf(name));
    }


    /* set using unsafe get */
    public <T> void setUnsafe(String name, T value) {
        /* might add handling of runtime exceptions */
        ((ValueObject<T>)get(name)).setValue(value);
    }

    /* safe get when client knows class */
    <T> ValueObject<T> get(String name, Class<T> clazz) {
        /* might do instanceOf check here to throw custom exception */
        return (ValueObject<T>) valueObjects.get(valueNames.indexOf(name));
    }

    /* set using safe get */
    public <T> void set(String name, T value) {
        /* might add handling of runtime exceptions */
        get(name, (Class<T>) value.getClass()).setValue(value);
    }
}

Upvotes: 1

Related Questions