Re: No coercion in for-each loop?
- From: bcd@xxxxxxxxxxx (Bent C Dalager)
- Date: Sun, 28 Oct 2007 10:44:14 +0000 (UTC)
In article <1193566420.335822.13500@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
crazzybugger <ajaykumarns@xxxxxxxxx> wrote:
On Oct 28, 5:31 am, Dave Stallard <stall...@xxxxxxxxxx> wrote:
List ar = new ArrayList();
ar.add(1);
List<String> list = ar;
for (String s : list)
Utils.log(s);
It is true that the compiler does not mind when you code
List<String> list=ar even though ar may contain non String objects. It
does so because, you are knowingly doing it and telling the compiler,
"See compiler, I am sure this list contains only String items and if
any error occurs I will manage it".
I don't see that you are saying this in the above code. What you are
saying is "As far as I recall, 'ar' is actually a List<String> so this
should work a treat" - much as if you had written
Object o = ...;
String text = o;
The compiler doesn't accept the latter, why should it accept the
former? Shouldn't it /require/ you to write
List<String> list = (List<String>) ar;
in the same way that it requires
String text = (String) o;
?
(Not that the cast would do you any good though, since
List ar = new ArrayList<Integer>();
ar.add(1);
List<String> list = (List<String>) ar;
for (String s : list)
System.out.println(s);
doesn't actually barf on the cast, but on the for statement. This
might be the reason I suppose - Java doesn't require the explicit cast
because it's unable to verify it anyway. This doesn't really improve
the situation in my eyes. But we may just be rehashing old complaints
about the generics system here.)
Cheers,
Bent D
--
Bent Dalager - bcd@xxxxxxx - http://www.pvv.org/~bcd
powered by emacs
.
- References:
- No coercion in for-each loop?
- From: Dave Stallard
- Re: No coercion in for-each loop?
- From: crazzybugger
- No coercion in for-each loop?
- Prev by Date: Re: No coercion in for-each loop?
- Next by Date: Re: Great SWT Program
- Previous by thread: Re: No coercion in for-each loop?
- Next by thread: Re: No coercion in for-each loop?
- Index(es):
Relevant Pages
|