java 自己定义了一个泛型类 怎么初始化啊? 我知道不能传入简单类型的 但是把main方法里的int改为Integer还是要报错 纠结啊。。

jingaita 2010-12-09 08:32:12
public class ArrayIterator<T> {
private T[] contents;
private int count;
private int i = 0;
public ArrayIterator(T[] contents,int count){
this.contents = contents;
this.count = count;
}

public boolean hasNext()
{
if(i<count)
return true;
else return false;
}

public T next()
{
return contents[i++];
}
}
class M
{
public static void main(String[] args)
{
int[] a = {1,2,3,4,5,6};
ArrayIterator<int> ai = new ArrayIterator<int>(a,a.length);
}
}
...全文
320 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
jingaita 2010-12-10
  • 打赏
  • 举报
回复
谢谢大家了
eswn 2010-12-09
  • 打赏
  • 举报
回复
ArrayIterator<T>中的T必须是对象类型,不能是基本类型,按楼上的改就可以了。
sunyiz 2010-12-09
  • 打赏
  • 举报
回复
public class ArrayIterator<T> {
private T[] contents;
private int count;
private int i = 0;

public ArrayIterator(T[] contents, int count) {
this.contents = contents;
this.count = count;
}

public boolean hasNext() {
if (i < count)
return true;
else
return false;
}

public T next() {
return contents[i++];
}

public static void main(String[] args) {
Integer[] a = { 1, 2, 3, 4, 5, 6 };
ArrayIterator<Integer> ai = new ArrayIterator<Integer>(a, a.length);
for (Integer i : a) {
System.out.println(ai.next());
}
}
}


这样子,楼主看一下运行效果吧
Jlins 2010-12-09
  • 打赏
  • 举报
回复
+[Quote=引用 1 楼 sunyiz 的回复:]

这样写就可以了
a必须是Integer型数组,不能是int型数组

Java code
class M
{
public static void main(String[] args)
{
Integer[] a = {1,2,3,4,5,6};
ArrayIterator<Integer……
[/Quote]
sunyiz 2010-12-09
  • 打赏
  • 举报
回复
这样写就可以了
a必须是Integer型数组,不能是int型数组

	class M  
{
public static void main(String[] args)
{
Integer[] a = {1,2,3,4,5,6};
ArrayIterator<Integer> ai = new ArrayIterator<Integer>(a,a.length);
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧