分类:
2008-09-09 16:46:11
1 protected void collectionsExample() {
2 ArrayList list = new ArrayList();
3 list.add(new String("test string"));
4 list.add(new Integer(9)); // purposely placed here to create a runtime ClassCastException
5 inspectCollection(list);
6 }
7
8
9 protected void inspectCollection(Collection aCollection) {
10 Iterator i = aCollection.iterator();
11 while (i.hasNext()) {
12 String element = (String) i.next();
13 }
14 }
1 protected void collectionsExample() {
2 ArrayListlist = new ArrayList ();
3 list.add(new String("test string"));
4 // list.add(new Integer(9)); this no longer compiles
5 inspectCollection(list);
6 }
7
8
9 protected void inspectCollection(CollectionaCollection) {
10 Iteratori = aCollection.iterator();
11 while(i.hasNext()) {
12 String element = i.next();
13 }
14 }
1 public class ArrayListextends AbstractList {
2 // details omitted...
3 public void add(E element) {
4 // details omitted
5 }
6 public Iteratoriterator() {
7 // details omitted
8 }
9 }
1 publicT max(T t1, T t2) {
2 if (t1.compareTo(t2) > 0)
3 return t1;
4 else return t2;
5 }
1 Integer iresult = max(new Integer(100), new Integer(200));
2 String sresult = max("AA", "BB");
3 Number nresult = max(new Integer(100), "AAA"); // does not compile
ListstringList = new ArrayList (); //1
List
void printCollection(Collection
void printCollection(Collection> c)
{ for (Object e : c) {
System.out.println(e);
}}
class NonGen {
Object ob; // ob is now of type Object
// Pass the constructor a reference to
// an object of type Object
NonGen(Object o) {
ob = o;
}
// Return type Object.
Object getob() {
return ob;
}
// Show type of ob.
void showType() {
System.out.println("Type of ob is " +
ob.getClass().getName());
}
}
// Demonstrate the non-generic class.
public class NonGenDemo {
public static void main(String args[]) {
NonGen iOb;
// Create NonGen Object and store
// an Integer in it. Autoboxing still occurs.
iOb = new NonGen(88);
// Show the type of data used by iOb.
iOb.showType();
// Get the value of iOb.
// This time, a cast is necessary.
int v = (Integer) iOb.getob();
System.out.println("value: " + v);
System.out.println();
// Create another NonGen object and
// store a String in it.
NonGen strOb = new NonGen("Non-Generics Test");
// Show the type of data used by strOb.
strOb.showType();
// Get the value of strOb.
// Again, notice that a cast is necessary.
String str = (String) strOb.getob();
System.out.println("value: " + str);
// This compiles, but is conceptually wrong!
iOb = strOb;
v = (Integer) iOb.getob(); // runtime error!
}
}
class Example1{
private T t;
Example1(T o){
this.t=o;
}
T getOb(){
return t;
}
void ShowObject(){
System.out.println("对象的类型是:"+t.getClass().getName());
}
}
public class GenericsExample1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Example1examplei=new Example1 (100);
examplei.ShowObject();
System.out.println("对象是:"+examplei.getOb());
Example1examples=new Example1 ("Bill");
examples.ShowObject();
System.out.println("对象是:"+examples.getOb());
}
}
class TwoGen{
T ob1;
V ob2;
// Pass the constructor a reference to
// an object of type T.
TwoGen(T o1, V o2) {
ob1 = o1;
ob2 = o2;
}
// Show types of T and V.
void showTypes() {
System.out.println("Type of T is " +
ob1.getClass().getName());
System.out.println("Type of V is " +
ob2.getClass().getName());
}
T getob1() {
return ob1;
}
V getob2() {
return ob2;
}
}
public class GenericsExampleByTwoParam {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TwoGentgObj =
new TwoGen(88, "Generics");
// Show the types.
tgObj.showTypes();
// Obtain and show values.
int v = tgObj.getob1();
System.out.println("value: " + v);
String str = tgObj.getob2();
System.out.println("value: " + str);
}
}
class Stats{
T[] nums; // array of Number or subclass
// Pass the constructor a reference to
// an array of type Number or subclass.
Stats(T[] o) {
nums = o;
}
// Return type double in all cases.
double average() {
double sum = 0.0;
for(int i=0; i < nums.length; i++)
sum += nums[i].doubleValue();
return sum / nums.length;
}
}
public class GenericsExampleByHierarchy {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer inums[] = { 1, 2, 3, 4, 5 };
Statsiob = new Stats (inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
Statsdob = new Stats (dnums);
double w = dob.average();
System.out.println("dob average is " + w);
// This won't compile because String is not a
// subclass of Number.
// String strs[] = { "1", "2", "3", "4", "5" };
// Statsstrob = new Stats (strs);
// double x = strob.average();
// System.out.println("strob average is " + v);
}
}
class StatsWildCard{
T[] nums; // array of Number or subclass
// Pass the constructor a reference to
// an array of type Number or subclass.
StatsWildCard(T[] o) {
nums = o;
}
// Return type double in all cases.
double average() {
double sum = 0.0;
for (int i = 0; i < nums.length; i++)
sum += nums[i].doubleValue();
return sum / nums.length;
}
// Determine if two averages are the same.
// Notice the use of the wildcard.
boolean sameAvg(StatsWildCard> ob) {
if (average() == ob.average())
return true;
return false;
}
}
public class GenericsExampleByWildcard {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer inums[] = { 1, 2, 3, 4, 5 };
StatsWildCardiob = new StatsWildCard (inums);
double v = iob.average();
System.out.println("iob average is " + v);
Double dnums[] = { 1.1, 2.2, 3.3, 4.4, 5.5 };
StatsWildCarddob = new StatsWildCard (dnums);
double w = dob.average();
System.out.println("dob average is " + w);
Float fnums[] = { 1.0F, 2.0F, 3.0F, 4.0F, 5.0F };
StatsWildCardfob = new StatsWildCard (fnums);
double x = fob.average();
System.out.println("fob average is " + x);
// See which arrays have same average.
System.out.print("Averages of iob and dob ");
if (iob.sameAvg(dob))
System.out.println("are the same.");
else
System.out.println("differ.");
System.out.print("Averages of iob and fob ");
if (iob.sameAvg(fob))
System.out.println("are the same.");
else
System.out.println("differ.");
}
}
class TwoD {
int x, y;
TwoD(int a, int b) {
x = a;
y = b;
}
}
// Three-dimensional coordinates.
class ThreeD extends TwoD {
int z;
ThreeD(int a, int b, int c) {
super(a, b);
z = c;
}
}
// Four-dimensional coordinates.
class FourD extends ThreeD {
int t;
FourD(int a, int b, int c, int d) {
super(a, b, c);
t = d;
}
}
// This class holds an array of coordinate objects.
class Coords{
T[] coords;
Coords(T[] o) { coords = o; }
}
// Demonstrate a bounded wildcard.
public class BoundedWildcard {
static void showXY(Coords> c) {
System.out.println("X Y Coordinates:");
for(int i=0; i < c.coords.length; i++)
System.out.println(c.coords[i].x + " " +
c.coords[i].y);
System.out.println();
}
static void showXYZ(Coords extends ThreeD> c) {
System.out.println("X Y Z Coordinates:");
for(int i=0; i < c.coords.length; i++)
System.out.println(c.coords[i].x + " " +
c.coords[i].y + " " +
c.coords[i].z);
System.out.println();
}
static void showAll(Coords extends FourD> c) {
System.out.println("X Y Z T Coordinates:");
for(int i=0; i < c.coords.length; i++)
System.out.println(c.coords[i].x + " " +
c.coords[i].y + " " +
c.coords[i].z + " " +
c.coords[i].t);
System.out.println();
}
public static void main(String args[]) {
TwoD td[] = {
new TwoD(0, 0),
new TwoD(7, 9),
new TwoD(18, 4),
new TwoD(-1, -23)
};
Coordstdlocs = new Coords (td);
System.out.println("Contents of tdlocs.");
showXY(tdlocs); // OK, is a TwoD
// showXYZ(tdlocs); // Error, not a ThreeD
// showAll(tdlocs); // Erorr, not a FourD
// Now, create some FourD objects.
FourD fd[] = {
new FourD(1, 2, 3, 4),
new FourD(6, 8, 14, 8),
new FourD(22, 9, 4, 9),
new FourD(3, -2, -23, 17)
};
Coordsfdlocs = new Coords (fd);
System.out.println("Contents of fdlocs.");
// These are all OK.
showXY(fdlocs);
showXYZ(fdlocs);
showAll(fdlocs);
}
}
public class ArrayListGenericDemo {
public static void main(String[] args) {
ArrayListdata = new ArrayList ();
data.add("hello");
data.add("goodbye");
// data.add(new Date()); This won't compile!
Iteratorit = data.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
}
}
public class HashDemoGeneric {
public static void main(String[] args) {
HashMapmap = new HashMap ();
map.put(1, "Ian");
map.put(42, "Scott");
map.put(123, "Somebody else");
String name = map.get(42);
System.out.println(name);
}
}
interface MinMax> {
T min();
T max();
}
// Now, implement MinMax
class MyClass> implements MinMax {
T[] vals;
MyClass(T[] o) { vals = o; }
// Return the minimum value in vals.
public T min() {
T v = vals[0];
for(int i=1; i < vals.length; i++)
if(vals[i].compareTo(v) < 0) v = vals[i];
return v;
}
// Return the maximum value in vals.
public T max() {
T v = vals[0];
for(int i=1; i < vals.length; i++)
if(vals[i].compareTo(v) > 0) v = vals[i];
return v;
}
}
public class GenIFDemo {
public static void main(String args[]) {
Integer inums[] = {3, 6, 2, 8, 6 };
Character chs[] = {'b', 'r', 'p', 'w' };
MyClassiob = new MyClass (inums);
MyClasscob = new MyClass (chs);
System.out.println("Max value in inums: " + iob.max());
System.out.println("Min value in inums: " + iob.min());
System.out.println("Max value in chs: " + cob.max());
System.out.println("Min value in chs: " + cob.min());
}
}
interface Executor{
void execute() throws E;
}
public class GenericExceptionTest {
public static void main(String args[]) {
try {
Executore =
new Executor() {
public void execute() throws IOException
{
// code here that may throw an
// IOException or a subtype of
// IOException
}
};
e.execute();
} catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
}