1.需要重写id的equals()方法。通过id比较对象是否相等
package com.easzz.entity;
public class Book {
private String id;
private String name;
private String price;
private String author;
public Book(String id, String name, String price, String author) {
super();
this.id = id;
this.name = name;
this.price = price;
this.author = author;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public Book() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
上面是Book实体类。
package com.easzz.global;
import java.util.ArrayList;
import java.util.List;
import com.easzz.entity.Book;
public class BooksGlobal {
private static List<Book> books;
static{
books=new ArrayList<Book>();
books.add(new Book("1","水浒传","19","施耐庵"));
books.add(new Book("2", "三国演义", "43", "罗贯中"));
books.add(new Book("3", "红楼梦", "123", "曹雪芹"));
books.add(new Book("4", "西游记", "34", "吴承恩"));
}
public static List<Book> getBooks(){
return books;
}
public static Book getBookById(String id){
Book book=new Book();
book.setId(id);
return books.get(books.indexOf(book));
}
}