[Bluej-discuss] bluej-discuss Digest, Vol 32, Issue 5

Stephen Bloch sbloch at adelphi.edu
Mon Feb 13 01:30:25 GMT 2006


JD <dnaltrop at gmail.com> writes:

>     /**
>      * Show he fifth item currently in the notebook.
>      */
>     public void fifthItem()
>     {
>         System.out.println(notes.get(4));
>     }
>
>
>The above works fine.  But it really isn't a return of a value but rather
>the output of a value.  When I try to return a value with the code below I
>get an error.  What am I doing wrong?
>
>
>/**
>      * Show he fifth item currently in the notebook.
>      */
>     public String fitfhItem()
>     {
>         return notes.get(4);
>     }
>
>I get an "incompatible types - found java.lang.Object but expected
>java.lan.String".  Why is this.  Isn't the item held in the array a string?

Excellent question.  The answer is "yes and no".  If you're the one 
who put things into "notes" (somewhere else in your program), YOU 
know that the things you put in are Strings... but the compiler, 
looking only at the above code, has no way of knowing that they are 
Strings.  All the compiler knows for certain is that they are 
Objects, since that's the declared return type of the 
ArrayList.get(int) method.

The standard way around this problem (at least, before Java 1.5) is 
to explicitly cast the result to String, e.g.
	return (String)(notes.get(4));
In other words, you're telling the compiler "Trust me, it's a String, 
and if it isn't, I'll accept the blame."  The compiler, in turn, 
agrees to "trust but verify" (to quote Ronald Reagan): at 
compile-time, it treats the expression as a String, so the method 
compiles successfully; but at run-time, it checks that the thing 
returned by notes.get(4) really IS a String, and if not, it throws a 
ClassCastException.

In Java 1.5 there are ways you can declare something to be an 
"ArrayList of Strings".  The task of checking whether the things in 
it really ARE Strings is shifted from run-time in the method that 
extracts something and casts it to String, to compile-time in the 
method that puts something IN (it won't allow you to put in something 
that isn't a String).  This both makes your program simpler and 
easier to read, and saves a little bit of run-time efficiency.
-- 
					Stephen Bloch
					sbloch at adelphi.edu


More information about the bluej-discuss mailing list