Java 关于说明泛型类语法用法的示例
在Java思考中,第566页给出了以下示例Java 关于说明泛型类语法用法的示例,java,Java,在Java思考中,第566页给出了以下示例 class CountedInteger { private static long counter; private final long id = counter++; public String toString() { return Long.toString(id); } } public class FilledList<T> { private Class<T> type; public Fi
class CountedInteger {
private static long counter;
private final long id = counter++;
public String toString() { return Long.toString(id); }
}
public class FilledList<T> {
private Class<T> type;
public FilledList(Class<T> type) { this.type = type; }
public List<T> create(int nElements) {
List<T> result = new ArrayList<T>();
try {
for(int i = 0; i < nElements; i++)
result.add(type.newInstance());
} catch(Exception e) {
throw new RuntimeException(e);
}
return result;
}
public static void main(String[] args) {
FilledList<CountedInteger> fl = new FilledList<CountedInteger>(CountedInteger.class);
System.out.println(fl.create(15));
}
}
类计数整数{
专用静态长计数器;
私有最终长id=计数器++;
公共字符串toString(){return Long.toString(id);}
}
公共类填充列表{
私人阶级类型;
公共填充列表(类类型){this.type=type;}
创建公共列表(整数元素){
列表结果=新建ArrayList();
试一试{
对于(int i=0;i
关于这个例子,我有三个问题
1) 私有类类型的用法是什么?为什么是私人的
2) 为什么要这样做,特别是“this.type=type;”
公共填充列表(类类型){this.type=type;}
3) 提交人声称:
注意,这个类必须假定它使用的任何类型
有一个默认构造函数(一个没有参数的构造函数),您将得到一个
如果情况并非如此,则例外
我想不出这句话是如何反映在上述例子中的。谢谢。1)不必这样,但这是您在Java中所做的事情之一——不要公开不需要公开的内容
2) 它将属性设置为构造函数的参数——这是基本Java
3) 因为type.newInstance()
调用;如果没有默认(无参数)构造函数,它将失败
type
的实例字段。关键字this
表示它是一个this实例字段type.newInstance()
代码将失败java.util.Collections.fill(list,value)
call
类型
只是另一个实例变量。它被宣布为私人的
以防止从该类之外访问它FilledList
的实例时,即
调用接受1个参数的构造函数,实例变量type
为
使用在构造函数中传递的此参数值初始化type.newInstance()
所做的是调用默认的无参数构造函数
对于这种类型,如果默认值为
构造函数是私有的1:一个类的所有成员都应该是私有的或受保护的。但是你不必那么做 2:在任何方法中,您都可以访问该类中的所有参数和所有成员变量。在本例中,参数名称与成员变量完全相同。因此,在这种情况下,如果您编写
类型
,参数名将获胜this
指向当前实例,使用this.type
表示您指的是成员变量,而不是参数。因此,在本例中,this.type=type
是member=parameter
3:如果没有参数,将调用T上的默认构造函数,如果它不存在,将抛出异常。看看这个链接
public FilledList(Class<T> type) { this.type = type; }