2

I have an ArrayList<Clause> called listtable. For some reason Clause[] whatever = listtable.toArray() gives an incompatible types error but Clause[] whatever = listtable.toArray(new Clause[0]) works just fine. Why is this so? What is the difference between the two calls? The javadoc says they are "identical in function".

Here is my full code (the relevant statement is right before the end):

public static Clause[] readCNF(String name,Boolean print) throws IOException 
    {
        BufferedReader file = new BufferedReader(new FileReader("./" + name));

        ArrayList<Clause> listtable = new ArrayList<Clause>();
        String line = null; 
        while ((line = file.readLine()) != null) {

            if(line.charAt(0) == 'p')
            {
                 Scanner scanner = new Scanner(line); 
                 scanner.next(); scanner.next(); Clause.NumVars = scanner.nextInt(); Clause.NumClauses = scanner.nextInt(); 

            } else if(line.charAt(0) != 'c') {  

                 ArrayList<Integer> lits = new ArrayList<Integer>();
                 Scanner scanner = new Scanner(line);

                 while(scanner.hasNext())
                 {
                     int var = scanner.nextInt();
                     if(var != 0){ lits.add(var);}
                 }

                 listtable.add(new Clause(lits));

            } 
        }

        if(print) {
            for(Clause clause : listtable)
            {
                clause.print();
            }
        }

       return(listtable.toArray(new Clause[0])); //since the return type is Clause[] this is the same as the statements in the question
    }
Elliot Gorokhovsky
  • 3,034
  • 2
  • 28
  • 47

1 Answers1

3

toArray() returns an array of Object. You have to cast every element of the array to your desired type.

The toArray(T[]) accepts a generic type and returns an array of the specific type. No need to cast the return value and/or the elements of the array.

As stated in the comments above, the toArray() method came pre-generics.

    List<String> list = new ArrayList<String>();
    list.add("Alice");
    list.add("Bob");

    String[] strArray = list.toArray(new String[0]);
    for (String str : strArray) {
        System.out.println(str);
    }

    Object[] objArray = list.toArray();
    for (Object obj : objArray) {
        String str = (String) obj;
        System.out.println(str);
    }
Sergio
  • 368
  • 1
  • 6