import java.util.*; public class Question2Main{ public static void main(String[] args){ // 1 List lp = new ArrayList(); // 2 //lp.add("Ohno"); // gives error // cannot find symbol - method add(java.lang.String) // 3. lp.add(new Person("Hans Knudsen", 1975) ); lp.add(new Student("Sara Pihl", 1987 ) ); // 4 Person p; Student s; //a) lp.get(1) returns a Student object //b) lp is a list of Person, so the compiler think // the object returned is of type person - you cannot assign person // to Student //c) You tell the compiler that the object returned is actually // a Student. The compiler accepts this, but tell the run-time // system to check it when the program is executed. //d) We know that it is a list of Person - so we do not need to // cast to Person. Also, if we intend this to be a list of Person, // the compiler will tell us if we by accident puts a String or Car // into the list. // 5 List ls; // 1) OK, I remember this :-) // 2) assigning ls=lp gives the error //ls = lp; // incompatible types - found java.util.List but expected // java.util.List // This means that the compiler will not assign a list of Person's to // a list of Students // 3) // If the assignment were allowed, ls could contain elements which were // general persons and not students. When we get an element from the list // we can no longer be sure to get a student. So we disallow the // assignement // 4) // the other way around is somewhat similar, lp and ls would refer to the // SAME Student list. But it would be allowed to add new persons to lp, // and because these lists are the same, a Person would be added to the // student list. This is what we do not want. // 5) // OK, the thing to remember is that a method // void doStuff(List lp) // cannot be called with a student list as actual parameter. // 6 // 1) List lep; // = new ArrayList(); // The syntax can be used only for declaration // of variables (fields, parameters, and local variables). It cannot // be used as a concrete type when objects are instantiated. // We can not make an instance of a list without specifying a concrete // type as type. // You can initialize lep by assigning it an existing list, or a // concrete list as new ArrayList. // 2) Yes, (lpp was ment to be lep) //lep = lp; // 3) Yes //lep= ls; // 4) No //lep.add( s ); // You cannot add elements to lep, because we do not know what type // of elements are really in the list. // 5) Yes, // we know that the list contains somekind of Persons // 7 Map map = new HashMap(); // 8 map.put("Lars", new Person("Lars", 1988)); map.put("Sidd", new Person("Siddartha", 1977)); // 9 p = map.get("Lars"); // OK // s = map.get("Sidd"); Not OK, the method returns something of // type Person, which cannot be assigned to a student reference. } }