java - Non-generic object of generic type -
for following codes:
arraylist<string> ar = new arraylist<string>(); ar.add(45);
and
arraylist<string> ar = new arraylist(); ar.add(45);
i getting compile time error @ line ar.add(45)
as:
cannot find symbol symbol : method add(int) location: class java.util.arraylist<java.lang.string> al.add(45); ^
both piece of code failing invalid input . why compiler raising warning of unchecked or unsafe operation second piece of code?
then why compiler raising warning of unchecked or unsafe operation second piece of code?
because you're assigning arraylist
variable type arraylist<string>
. means while compiler enforce expectation array list contain strings when reference list through ar
, can't sure don't have other references non-parameterized arraylist
you'll use add non-strings it, this:
arraylist anythinggoes = new arraylist(); arraylist<string> onlystrings = anythinggoes; // unchecked/unsafe op anythinggoes.add(new date()); (string s : onlystrings) { // blows // ... }
Comments
Post a Comment