By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,798 Members | 1,342 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,798 IT Pros & Developers. It's quick & easy.

1.5 generic question

P: n/a
Has anyone had a play with generics in the JDK1.5 beta-release and/or
knows the answer to this:

If I have the following:

// immutable
interface Address
{
String getStreet() { ... }
...
}

// mutable
class MutableAddress implements Address
{
String getStreet() { ... }
void setStreet( String street ) { ... }
}

then using generics I could define this:

private List<MutableAddress> list;

but could I 'down-cast' this list to do the following:

List<Address> getList() { return list; }

i.e. the client will only get the immutable base-class.

Any ideas?

- sarge
Jul 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
then using generics I could define this:

private List<MutableAddress> list;

but could I 'down-cast' this list to do the following:

List<Address> getList() { return list; }


No you can't. Otherwise, your client would be able to add an Address
which is not a MutableAddress in the list, which would make the type of
your private list field a fallacy.

So if you want such behaviour, you need to guarantee that the client
will not modify the original list. There are (at least) two ways to do
that: return a copy of the list, or return an unmodifiable version of
the list:

List<Point> get() = new ArrayList(l);

List<Point> get() = Collections.unmodifiableList(l);

These method definitions are in the syntax of Nice (the syntax = ...; is
a short-hand for { return ...; }). If expect the same idea will work in
Java 1.5, if they gave the right types to these operations, which was
not always the case as far as I could experience... Does anybody with
access to the prototype can test it?

Daniel

The Nice extension of Java: http://nice.sf.net

Jul 17 '05 #2

P: n/a
That is what OO inheritance means.
It works one way only. Try the other direction.
"Chris" <sa*********@hotmail.com> wrote in message
news:56*************************@posting.google.co m...
Has anyone had a play with generics in the JDK1.5 beta-release and/or
knows the answer to this:

If I have the following:

// immutable
interface Address
{
String getStreet() { ... }
...
}

// mutable
class MutableAddress implements Address
{
String getStreet() { ... }
void setStreet( String street ) { ... }
}

then using generics I could define this:

private List<MutableAddress> list;

but could I 'down-cast' this list to do the following:

List<Address> getList() { return list; }

i.e. the client will only get the immutable base-class.

Any ideas?

- sarge

Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.