Re: exporting a HashMap
On Mon, 16 Jan 2012 14:19:20 -0800, Lew <noone@lewscanon.com> wrote,
quoted or indirectly quoted someone who said :
Generics and arrays do not mix well. That's because arrays "remember" their
underlying type at runtime, but generics just become 'Object' at runtime
through the process of "type erasure". [1] The compiler will not let you
create an array of generic types, unless the generic parameter comprises
entirely unadorned wildcard ('?') characters. So
Foo<?> [] bunchaFoos = new Foo<?> [NUMFOOS];
is legal, but
Foo<Bar> [] bunchaFoos = new Foo<Bar> [NUMFOOS];
is not. Other things like casting and reflection get really difficult, too.
For almost everything you want to do mixing arrays and generics you can use
'ArrayList' instead of an array. The syntax is a little more verbose but the
type safety and expressiveness compensate.
[1] In technical terms, an array is a "reifiable" type - it can be made "real"
in the JVM. Consequently its base type must also be reifiable. A generic
type, except for the pure wildcard '?' generics, is not reifiable because of
erasure. So the compiler won't let you make an array of a generic type.
I have added this to http://mindprod.com/jgloss/generics.html with
attribution.
There is an outstanding question your entry triggered:
/*
* @(#)Alphabetically.java
*
* Summary: Describe/summarise the comparison here..
*
* Requires: JDK 1.5+
*
* Created with: Canadian Mind Products ComparatorCutter.
*
* Version History:
* 1.0 2012-01-17 - initial release
*/
// <> package ...
import java.util.Comparator;
/**
* Describe/summarise the comparison here..
* <p/>
* Defines an alternate sort order for Thing.
*
* @author ...
* @version 1.0 2012-01-17 - initial release
* @since 2012-01-17
*/
class Alphabetically implements Comparator<Thing>
{
/**
* Describe/summarise the comparison here..
* Defines an alternate sort order for Thing with JDK 1.5+
generics.
* Compare two Thing Objects.
* Compares name case sensitively.
* Informally, returns (a-b), or +ve if a sorts after b.
* The Java source code for this Comparator was generated by the
* Canadian Mind Products ComparatorCutter Applet at
http://mindprod.com/applet/comparatorcutter.html
* For non-military purposes only.
*
* @param a first Thing to compare
* @param b second Thing to compare
*
* @return +ve if a>b, 0 if a==b, -ve if a<b
*/
public final int compare( @NotNull Thing a, @NotNull Thing b )
{
return a.name.compareTo( b.name );
}
}
at run time, what type are the parameters to compare, Thing or Object?
--
Roedy Green Canadian Mind Products
http://mindprod.com
One of the most useful comments you can put in a program is
"If you change this, remember to change ?XXX? too".