// CSE 332, Winter 2011 - Section Week 1 worksheet public class Bag { private E item; public void setItem(E x) { item = x; } public E getItem() { return item; } public static void main(String[] args) { Bag bagInt=new Bag(); bagInt.setItem(new Integer(42)); Bag bagStr=new Bag(); bagStr.setItem("A very fine string"); //which of the following (if any) are legal? //bagInt.setItem("A very fine string"); //bagInt.setItem("42"); //bagStr.setItem(new Integer(42)); //bagStr.setItem(new Object()); //bagInt=bagStr; //bagInt.setItem(42); //Bag> bagBag=new Bag>(); //this is apparently legal; what type is 'E'? Bag someBag=new Bag(); /* //what's wrong with the following code (once uncommented)? String s="x"; someBag.setItem(s); s=someBag.getItem(); */ } public void createGenericArrayTest() { //E[] myGenericArray=new E[128]; //But this gives a compilation error: Cannot create a generic array of E //To get around this, you can create an Object array and cast it, like this: //E[] myGenericArray=(E[])new Object[128]; } }