I try to populate ArrayLists with random values. The Arraylists can contain either Strings, Integers, Doubles or Chars. Creating random values works fine, but my Problem is that I am not able to write my insertRandom method. It should insert a specific data type (like double, int, etc). I described below what I want my insertRandom method to do. I am getting the warning "The method insert(T) in the type buffer is not applicable for the arguments(int). I googled it but did not find out / did not understand how to typecast my values to T objects, or how to check (similar to what "instanceof" does), what data types my ArrayLists contain. I already read about class types that people used as parameters in their constructor, but I am not allowed to change the parameter list of my constructor.
public class Buffer <T> {
private ArrayList<T> list;
// constructor
public Buffer (int capacity) {
this.list = new ArrayList<T>();
}
// insert items to buffer
public void insert (T item) {
list.add(item);
}
// insert random values
public void insertRandom () {
check if ArrayList is of type String / Integer / Double
if (ArrayList is-of-type-String) {
insert("ThisString");
}
if (ArrayList is-of-type-Double) {
insert(3.4);
}
}
Thanks and best greetings, Patrick