Cách sử dụng ArrayList trong Java
package arrayListDemo;
import java.util.*;
class student {
int id;
String name;
float GPA;
public student(int id, String name, float GPA) {
this.id = id;
this.name = name;
this.GPA = GPA;
}
public student() {
this.id = 0;
this.name = "";
this.GPA = 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getGPA() {
return GPA;
}
public void setGPA(float gPA) {
GPA = gPA;
}
void input() {
Scanner objSc = new Scanner(System.in);
System.out.print("id:");
this.setId(objSc.nextInt());
objSc.nextLine();
System.out.print("Name:");
this.setName(objSc.nextLine());
System.out.print("GPA:");
this.setGPA(objSc.nextFloat());
}
void output() {
System.out.println("id " + this.getId() + "Name: " + " " + this.getName() + "GPA: " + this.GPA);
}
}
class listOfSt {
ArrayList<student> list = new ArrayList<student>();
void input(student[] st) {
for (int i = 0; i < st.length; i++) {
st[i] = new student();
st[i].input();
list.add(st[i]);
}
}
void output() {
for (int i = 0; i < list.size(); i++) {
list.get(i).output();
}
}
void findName(String name) {
char c = 'N';
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getName().contains(name)) {
System.out.println("Tim thay:");
c = 'Y';
list.get(i).output();
break;
}
}
if (c == 'N') {
System.out.println("KHong tim thay!");
}
}
void delete(int id) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getId() == id) {
list.remove(id);
}
}
}
}
public class demo {
public static void main(String[] args) {
Scanner objSc = new Scanner(System.in);
int idelete;
String name;
student st[] = new student[3];
listOfSt list = new listOfSt();
list.input(st);
list.output();
System.out.print("Ten can tim:");
name = objSc.nextLine();
list.findName(name);
System.out.print("Nhap ma sinh vien can xoa:");
idelete = objSc.nextInt();
list.delete(idelete);
list.output();
}
}
Trương Đình Huy