package ArrayListDemo;
public class Student {
//1.私有化成员变量
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package ArrayListDemo;
import java.util.ArrayList;
public class ArrayList4 {
public static void main(String[] args) {
//1.创建集合
ArrayList<Student> list = new ArrayList<Student>();
//2.创建学生对象
Student s1 = new Student("zhangsan",18);
Student s2 = new Student("lisi",19);
Student s3 = new Student("wangwu",20);
//3.添加元素
list.add(s1);
list.add(s2);
list.add(s3);
//4.遍历集合
for (int i = 0; i < list.size(); i++) {
//i 索引 list.get(i) 元素/学生信息
Student stu = list.get(i);
System.out.println(stu.getName()+","+stu.getAge());
}
}
}
增加功能,可以进行手动输入数据
package ArrayListDemo;
import javax.naming.Name;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListDemo5 {
public static void main(String[] args) {
//1.创建集合
ArrayList<Student> list = new ArrayList<Student>();
//2.键盘录入学生信息并添加到集合当中
Scanner sc =new Scanner(System.in);
for (int i = 0; i < 3 ; i++) {
Student st = new Student();
System.out.println("请输入学生姓名");
String name = sc.next();
System.out.println("请输入学生年龄");
int age = sc.nextInt();
//3.把name和age赋值给学生
st.setName(name);
st.setAge(age);
list.add(st);
}
for (int i = 0; i < list.size(); i++) {
//i 索引 list.get(i) 元素/学生信息
Student stu = list.get(i);
System.out.println(stu.getName()+","+stu.getAge());
}
}
}
package ArrayListDemo;
import java.util.ArrayList;
public class ArrayListDemo6 {
public static void main(String[] args) {
//1.创建集合
ArrayList<User> list = new ArrayList<User>();
//2.创建三个对象
User u1 = new User("jinrong001", "zhangsan", "zs2002");
User u2 = new User("jinrong002", "lisi", "ls2002");
User u3 = new User("jinrong003", "wangwu", "ww2003");
//3.把用户对象加入到集合当中
list.add(u1);
list.add(u2);
list.add(u3);
//4.调用方法,查看id是否存在
boolean flag = contains(list, "jinrong001");
System.out.println(flag);
}
//1.我要干嘛 根据id查找用户
//2.我干这件事情需要什么才能完成 在list找id
//3.调用处是否需要使用方法的结果 返回
public static boolean contains(ArrayList<User> list , String id){
for (int i = 0; i < list.size(); i++) {
boolean uid = list.get(i).getId().equals(id);
if(uid){
//如果找到了返回true
return true;
}
}
//当循环结束还是没有一样的返回false;
return false;
}
}