0

I have following sample code on java generics. Code:

public class SampleClass<T> {
ArrayList<T> arrayList;

SampleClass() {
    arrayList = new ArrayList<T>();
}

void addElementToList(T item) {
    arrayList.add(item);
}

public void printArrayList(){
    for (T element: arrayList) {
        System.out.println(element);
    }
}

}

class MainClass{
public static void main(String[] args) {
        SampleClass sampleClass = new SampleClass();
        sampleClass.addElementToList("ele1");
        sampleClass.addElementToList("ele2");
        sampleClass.addElementToList(123);
        sampleClass.printArrayList();

}

}

output:

ele1
ele2
123

So as property of ArrayList, it must contain homogeneous type of elements in it. But the above code is contradicting this. So is it possible? Means why JVM allowing it to happen?

Saurabh kukade
  • 1,608
  • 12
  • 23
  • ^^ +1. Constructing SampleClass without any type parameter (raw type) roughly means any Object can be added as an element (roughly, because basically skips the type checking), the rest is autoboxing and the fact that class Object is the root of the class hierarchy. – István Őri Nov 24 '17 at 11:48

1 Answers1

0

You didn't pass the required type in to SampleClass

Ex:

SampleClass<String> sc = new SampleClass<>(); 
pecks
  • 318
  • 1
  • 2
  • 9