01/10/2018, 08:30
Cách gọi phương thức tìm kiếm trong ArrayList
Em không thế nào gọi được phương thức tìm kiếm (searchMobile)
Với lại em cũng không hiểu các sử dụng phần boolean addMobile, editMobile, dellMobile.
import java.util.*;
public class MobileManager {
// Constants
public static final short MAX_MOBILE = 1000;
// Object's properties
private ArrayList<Mobile> list;
// Constructor
public MobileManager() {
this.list = new ArrayList<Mobile>();
}
public MobileManager(int n) {
this.list = new ArrayList<Mobile>(n);
}
// Other methods
public boolean addMobile(Mobile m) {
if (this.list.size() < MobileManager.MAX_MOBILE) {
this.list.add(m);
return true;
} else
return false;
}
public boolean editMobile(Mobile m) {
Mobile item;
for (int i = 0; i < this.list.size(); i++) {
item = this.list.get(i);
if (item.getProduct_id() == m.getProduct_id()) {
this.list.set(i, m);
return true;
}
}
return false;
}
public boolean delMobile(Mobile m) {
Mobile item;
for (int i = 0; i < this.list.size(); i++) {
item = this.list.get(i);
if (item.getProduct_id() == m.getProduct_id()) {
this.list.remove(i);
return true;
}
}
return false;
}
public ArrayList<Mobile> searchMobile(String name) {
ArrayList<Mobile> result = new ArrayList<Mobile>();
for (Mobile m : this.list) {
if (m.getProduct_name().contains(name)) {
result.add(m);
}
}
return result;
}
public void generateList(int n) {
String[] manufactures = { "samsung", "apple", "sony" };
String[] screen = { "2 inches", "4 inches", "5 inches" };
String[] models = { "2015", "2016", "2017" };
for (int i = 1; i <= n; i++) {
Mobile m = new Mobile();
byte index = (byte) (Math.random() * manufactures.length);
m.setMobile_manufactury(manufactures[index]);
index = (byte) (Math.random() * screen.length);
m.setMobile_screen(screen[index]);
index = (byte) (Math.random() * models.length);
m.setMobile_model(models[index]);
m.setMobile_weight((short) (Math.random() * 1000));
m.setProduct_id((short)i);
m.setProduct_name(m.getMobile_manufactury()+", "+m.getMobile_model());
m.setProduct_price((int) (Math.random() * 1000000));
m.setProduct_total((short) (Math.random() * 1000));
if(!addMobile(m)){
break;
}
}
}
public void printList(){
for(Mobile m: this.list){
System.out.println(m);
}
}
public static void main(String[] args) {
MobileManager mm = new MobileManager();
mm.generateList(10);
mm.printList();
System.out.println("Ket qua tim kiem");
}
}
Bài liên quan
Để dùng được phương phức searchMobile() thì em phải Override phương thức equals() trong class Mobile. Giả sử class Mobile của em có các thuộc tính manufactures, screee, models thì có thể override như sau: