TICS Coding Standard Viewer 
TIOBE Software Quality Framework
Print-friendly version
©TIOBE Software www.tiobe.com
 
TIOBE - Java Coding Standard
Search

Rule:  Basic22Checked automatically with code checker

Synopsis:This usage of the Collection.toArray() method will throw a ClassCastException
Language:Java
Severity Level:1
Category:Basic


Description:
if you need to get an array of a class from your Collection, you should pass an array of the desidered class as the parameter of the toArray method. Otherwise you will get a ClassCastException.
import java.util.ArrayList;
import java.util.Collection;

public class Test {

    public static void main(String[] args) {
        Collection c=new ArrayList();
        Integer obj=new Integer(1);
        c.add(obj);

        // this would trigger the rule (and throw a ClassCastException
if executed)
        Integer[] a=(Integer [])c.toArray();

        // this wouldn't trigger the rule
        Integer[] b=(Integer [])c.toArray(new Integer[c.size()]);
    }
}