forvirret over generics
HejJeg har som overskriften informerer om et problem angående generics.
Jeg har et spørgsmål der går på følgende:
Declare a List<? extends Person> lep.
0. How can you initialize the lep variable? Why can you not
write "new ArrayList<? extends Person>()"?
1. Can you make the assignment lpp = lp?
2. Can you make the assignment lpp = ls?
3. Can you insert elements into lpp? Why (not)?
4. Can you get elements from lpp?
Det står ikke helt klart for mig, hvordan det hænger sammen, når extends introduceres i de to brackets, jeg håber der er en venlig sjæl der kan hjælpe mig til et overblik.
Hvilken rolle har spørgsmålstegnet?!
På forhånd tak!!!
Klassen jeg opererer med ser ud som følger:
/* GenericTester.java
* Created on 2005-11-10
*/
package exercise02;
import java.util.*;
class Person {
String name;
Integer birthYear;
Person(String name, int birth){
this.name = name;
birthYear = birth; // boxing
}
Integer age(){
return 2004-birthYear; // unboxing & boxing
}
}
class Student extends Person{
String university;
Student(String name, int birth){
super(name, birth);
university = "ITU";
}
Student(String name, int birth, String university){
super(name, birth);
this.university = university;
}
}
public class GenericTester {
public static void main(String[] args) {
// 2.1
List<Person> lp = new ArrayList <Person>();
// 2.2
// list.add("String");
// error message:
// The method add(Person) in the type List<Person>
// is not applicable for the arguments (String)
// 2.3
lp.add(new Person("John Doe", 1873));
lp.add(new Student("Hasse Backe", 1958));
// 2.4
Person p;
Student s;
// 2.4.a - lp.get(1) returns a Person object, because the lists type parameter is Persons,
// thus only references to class Person and its subclasses can be put into the list
// and only Person references can be fetched from the list
p = lp.get(1);
// 2.4.b
// this produces an exception because a student reference is not applicable with
// a Person reference unless the down cast has been ensured by a type cast
// s = lp.get(1);
// 2.4.c
s = (Student)lp.get(1); // this works because of the type cast
// 2.4.d
// Generic methods are good because they allow us to write generic
// code and enables type checking at compile time instead of run time.
// This example only shows the power of type checking at compile time.
// 2.5
List <Student> ls = new ArrayList <Student>();
// 2.5.2
//ls = lp;
// exceotion: Type mismatch: cannot convert from List<Person> to List<Student>
// 2.5.3
// The assignment is illegal because of the difference in type parameters
// 2.5.4
//lp = ls;
// exception: Type mismatch: cannot convert from List<Student> to List<Person>
// The assignment is illegal because of the difference in type parameters
// 2.6
List <? extends Person> lep; // = new ArrayList <StreetEntertainer extends Person>();
}
}
