list literal gotcha and suggestion

Reinier Zwitserloot reinier at zwitserloot.com
Wed Oct 7 09:15:49 PDT 2009


Will you stop beating around the bush? What is it then?

What will this code print, and will the call to test() take O(1) or  
O(n) time?


public class Test {

     public void test(Collection<?> t) {
         System.out.println(t.size());
         System.out.println(t.contains("Hello"));
     }

     public static void main(String[] args) {
         test({"a", "b", "c", "a", "b", "c", /* 99,993 more strings  
*/, "Hello"});
     }
}


Will it take O(N) time and print '100000\ntrue\n', or will it take  
O(1) time and print '99997\ntrue\n'?

is this legal:

int x = 0;

{"a", "b"}.get(x)?


if it is, what new compiler magic will figure out that this literal  
must evidently be referring to a List, due to the get() call tacked on  
to it?




  --Reinier Zwitserloot



On 2009/07/10, at 18:00, Neal Gafter wrote:

> On Wed, Oct 7, 2009 at 8:55 AM, Reinier Zwitserloot <reinier at zwitserloot.com 
> > wrote:
> So, when passing {1, 2, 3} to a method that takes 1 Collection, it  
> will not, in fact, work without an explicit cast, then. Okay. As I  
> said, I think that's quite a serious use case.
>
> Correction: when passing {1, 2, 3} to a method that takes 1  
> Collection, it will, in fact, work without a cast.
>
> Before you suggest that, then, the construct will default to a List  
> - I'm not sure that's a good idea
>
> I'm suggesting that there be no such default.




More information about the coin-dev mailing list