Java 从第二行底部检查语法,我发现EclipseIDE中有错误

Java 从第二行底部检查语法,我发现EclipseIDE中有错误,java,arrays,arraylist,Java,Arrays,Arraylist,请在下面第二行找到错误,并向我解释发生错误的原因。您必须使用(示例)如下方式投射对象: import java.util.*; class sample { int rollno; String name; int age; sample(int rollno, String name, int age) { this.rollno = rollno; this.name = name; this.age =

请在下面第二行找到错误,并向我解释发生错误的原因。

您必须使用
(示例)
如下方式投射对象:

import java.util.*;

class sample {

    int rollno;
    String name;
    int age;

    sample(int rollno, String name, int age) {
        this.rollno = rollno;
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        sample s1 = new sample(1, "praveen", 22);
        sample s2 = new sample(2, "rajesh", 23);
        sample s3 = new sample(3, "ganesh", 24);
        sample s4 = new sample(4, "jyothi", 25);
        sample s5 = new sample(5, "sathish", 26);

        ArrayList al = new ArrayList();
        al.add(s1);
        al.add(s2);
        al.add(s3);
        al.add(s4);
        al.add(s5);

        Iterator itr = al.iterator();
        while (itr.hasNext()) {
            sample sa = itr.next();
            System.out.println(sa.rollno + " " + sa.name + " " + sa.age);
        }

    }
}
sample sa = (sample) itr.next();
或者,您可以像下面这样指定迭代器的类型:

import java.util.*;

class sample {

    int rollno;
    String name;
    int age;

    sample(int rollno, String name, int age) {
        this.rollno = rollno;
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        sample s1 = new sample(1, "praveen", 22);
        sample s2 = new sample(2, "rajesh", 23);
        sample s3 = new sample(3, "ganesh", 24);
        sample s4 = new sample(4, "jyothi", 25);
        sample s5 = new sample(5, "sathish", 26);

        ArrayList al = new ArrayList();
        al.add(s1);
        al.add(s2);
        al.add(s3);
        al.add(s4);
        al.add(s5);

        Iterator itr = al.iterator();
        while (itr.hasNext()) {
            sample sa = itr.next();
            System.out.println(sa.rollno + " " + sa.name + " " + sa.age);
        }

    }
}
sample sa = (sample) itr.next();
Iterator itr=al.Iterator();
只需使用
ArrayList al=new ArrayList()


为清晰起见

请阅读“修复缩进”,遵循类命名约定。格式化你的代码!来吧这个类甚至不可读!“请在下面的第二行中找到错误”-为什么不告诉我们您得到了什么错误并标记有问题的行?对我来说,“第二条底线”是“}”。)使用eclipse之类的代码编辑器,它会自动告诉您
类型不匹配:无法从对象转换为示例
,并提供修复选项
添加cast
其精细。“但我们为什么要这样做呢?”PraveenGandepalli如果你使用仿制药,你就不必这样做。如果您不知道为什么需要泛型或强制转换,您应该重新审视Java基础知识error@PraveenGandepalli因为您没有指定迭代器的类型,所以您也可以使用第二种解决方案来解决您的问题,请检查我的editya它现在是否工作。。给我一些关于它的解释,并可能使用
List al=…
:)@PraveenGandepalli您还有什么问题吗?@Thomas我认为这不能解决问题,您应该在迭代器中指定类型,而不是在ArrayList
Iterator itr=al.Iterator()中指定类型
我错了?@YCF_L如果定义
List al
(或
ArrayList
),则
al.iterator()
将返回一个
迭代器。如果你使用泛型,你应该始终如一地使用它。仅仅定义
List al
没有任何好处,因为编译器不知道允许进入
al
的内容,所以它不允许
Iterator itr=al.Iterator()-至少会发出警告。检查这个,检查这个你是怎么解释这个的@Thomas