public class BookList {
ArrayList bl =new ArrayList();
public void chunBan(){
Book b1= new Book();
b1.setBid(1);
b1.setName("java");
b1.setPrice(32.00);
bl.add(b1);
Book b2 = new Book();
b2.setBid(2);
b2.setName("c++");
b2.setPrice(56.00);
bl.add(b2);
}
public void chaXun(int bid) {
for (Book book : bl) {
if (book.getBid()==bid) {
System.out.println(book.getName()+"\t"+book.getPrice());
}
}
}
public void see() {
for (Book book : bl) {
System.out.println(book.getName());
}
}
public void update(int bid,double price) {
for (Book book : bl) {
if (book.getBid()==bid) {
book.setPrice(price);
}
}
}
public void remove2(int bid) {
for (Book book : bl) {
if (book.getBid()==bid) {
bl.remove(book);
}
}
}
public void jiXunChuBan(int bid,String name,double price) {
int k=bl.size();
Book b3 = new Book(bid,name,price);
bl.add(k,b3);
}
public void qingKong() {
bl.clear();
}
}
public class Book {
private int bid;
private String name;
private double price;
public Book(int bid, String name, double price) {
super();
this.bid = bid;
this.name = name;
this.price = price;
}
public Book() {
super();
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
public class BookMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
BookList blist = new BookList();
blist.chunBan();
blist.see();
blist.jiXunChuBan(3, "c", 59.00);
blist.see();
blist.remove2(3);
blist.see();
}
}
你线程操作同一个list等时,需要做互斥保护
public void remove2(int bid) {
for (Book book : bl) {
if (book.getBid()==bid) {
bl.remove(book);
}
}
}
用foreach方式循环遍历删除会报错
用for的方式
for(int i=bl.size()-1;i>=0;i--){
Book book = (Book)bl.get(i);
if (book.getBid()==bid) {
bl.remove(book);
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。