1. Dec 12th, 2006

    Go easy on the type checking

    This little piece of code compiles, but doesn’t work.

    public String[] getNamesOf(Collection people) {
      ArrayList<String> names = new ArrayList<String>();
      for (Person person : people)
        names.add(person.getName());
      return (String[]) names.toArray();
    }

    Now, interesting question: why would a type checking compiler allow this type checking error to pass through?

    Update: If you’re seeing this a second time in your feed reader, WP ate my brackets the first time, I fixed it to include the use of generics.

    1. Dec 12th, 2006

      Eran

      Shouldn’t you be using generics for this? I think the compiler would correctly catch the error if you used ArrayList (or ArrayList) instead of just ArrayList.

    2. Dec 12th, 2006

      Eran

      Dude! your blog ate my angle brackets!

      Shouldn’t you be using generics for this? I think the compiler would correctly catch the error if you used ArrayList<Person> (or ArrayList<String>) instead of just ArrayList.

    3. Dec 12th, 2006

      Assaf

      oops … it ate my angle brackets also, there was a <String> in there. let me try and fix it.

    Your comment, here ⇓