*import java.util.*;
public class UserArrayList {
public static void main(String[] args) {
//Creating user defined class objects
Student s1=new Student(1,"AAA",13);
Student s2=new Student(2,"BBB",14);
Student s3=new Student(3,"CCC",15);
ArrayList<Student> al=new ArayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
如何使用ArrayList检索Student类的单个属性,或检查列表中是否存在“ AAA”?
答案 0 :(得分:2)
只需添加两行和顺便说一句。创建ArrayList时,该代码有错误。您写的“ ArayList”是错误的。
方法1。
public static void main(String[] args) {
//Creating user defined class objects
Student s1=new Student(1,"AAA",13);
Student s2=new Student(2,"BBB",14);
Student s3=new Student(3,"CCC",15);
ArrayList<Student> al=new ArrayList<Student>(); // YOU HAVE MISTAKE HERE ArayList<Student>()
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
if(st.name.equals("AAA")) // LINE ADDED
System.out.println("present!"); // LINE ADDED
}
}
}
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
方法2-> Java 8或更高版本
Student find = al.stream().filter(s -> s.name.equals("AAA")).findFirst().orElse(null);
if(find != null)
System.out.println("AAA is present");