根据id拿到泛型集合中的对象

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
    //重写id的equals()方法 通过id比较对象。
    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() {
        // TODO Auto-generated constructor stub
    }
    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;
    }
    //根据id拿到属性为id的Book对象。
    public static Book getBookById(String id){
        Book book=new Book();
        book.setId(id);//设置传入的id值
        //books.indexOf()根据id比较对象是否相等

        return books.get(books.indexOf(book));
        //返回关联id的Book对象。
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值