0
package com.test.scjp;

import java.util.List;
import java.util.ArrayList;

public class TestGeneric {
    public static void main(String args[]){
        try{
            List<String> l = new ArrayList<String>();
            TestGeneric t = new TestGeneric();
        //t.test(l);
            System.out.println("Test");
            l=t.test(l);
            System.out.println("Test2");

            System.out.println(l.get(0));
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    public List<String> test(List l){
        System.out.println("Test0");
        l.add(new Integer(1));
        System.out.println("Test1");
        return l;
    }
}

When I run this code 20 times I am getting different outputs:

Output 1:

Test
Test0
Test1
Test2
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at com.test.scjp.TestGeneric.main(TestGeneric.java:16)

Output 2:

Test
Test0
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at com.test.scjp.TestGeneric.main(TestGeneric.java:16)
Test1
Test2
George Cummins
  • 28,485
  • 8
  • 71
  • 90
  • Test Test0 Test1 Test2 java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at com.test.scjp.TestGeneric.main(TestGeneric.java:16) – Rajesh Sahoo May 29 '13 at 21:52
  • `l.add(new Integer(1))` <-- you are trying to add an integer to a list containing String elements. – fge May 29 '13 at 21:54
  • 5
    Output in console comes from two streams, `System.out`, and `System.err`, and as you can see, sometimes output from `err` can be printed while printing output from `out`. To make it more readable IDEs like Eclipse use different color on `err`. – Pshemo May 29 '13 at 21:57
  • @Pshemo: you should make that an answer – JB Nizet May 29 '13 at 22:00
  • @JBNizet Nah, answer should fully explain this problem. I proffered to post general idea as comment and let others explain it better, since I am too tired and going to sleep now. Goodnight all :D – Pshemo May 29 '13 at 22:12

2 Answers2

2

System.out and System.err work on different threads. Both threads access a shared resource (the console) at different times.

See also Random printing order for System.out & System.err calls and Java: System.out.println and System.err.println out of order

Community
  • 1
  • 1
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
0

Inside test, your list isnt Generic - so you're allowed to add any Object to it.

The problem is that outside of it you're using a List that is restricted to Strings.

Its this conflict thats causing your problems.

pauljwilliams
  • 19,079
  • 3
  • 51
  • 79