KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Language: Java Compiler version: 1.6 In the below code, am trying to do the following: create a List<String> add a String assign List<String> to raw List create a List<Integer> assign the raw List to List<Integer> add an Integer retrieve the value using get() @ indexes 1 & 2 and print them. All statements are compiling (with warnings) and run fine. But if I try to loop through the List<Integer> using a for loop, I am getting a ClassCastException . I am just wondering why its allowed me to use list.get() method but not allowing me to iterate over it? Output: (if I run with un-commented for loop) abcd 200 Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at genericsamples.CheckRawTypeAdd.main(CheckRawTypeAdd.java:26) Here is my code import java.util.*; import java.io.*; class CheckRawTypeAdd { public static void main(String[] sr) { List<String> list_str = new ArrayList<String>(); list_str.add("abcd"); List<Integer> list_int = new ArrayList<Integer>(); List list_raw; list_raw=list_str; list_int=list_raw; list_int.add(200); Object o1 = list_int.get(0); Object o2 = list_int.get(1); System.out.println(o1); System.out.println(o2); //for(Object o : list_int) //{ // System.out.println("o value is"+o); //} } }
Tags (comma-separated)
Save Edits
Cancel