【问题标题】:how to compare avoid insertion of duplicate data into arraylist如何比较避免将重复数据插入arraylist
【发布时间】:2012-11-11 10:12:50
【问题描述】:

我有一个类,我根据提供的 id 将数据插入到数组列表中。 我正在将一个 bookId 传递给我的班级,并通过比较 bookid 我得到一个 book 对象。在得到那个对象(书)之后,我插入到我的数组列表中。 现在我不想多次插入相同的数据。如果同一个 bookid 在类中传递,那么它应该只存储一次。
我将我的数组列表存储到会话中。

请检查我的代码。并为我的问题建议一个解决方案。如何避免将数据重复插入到我的数组列表中?

AddBookToSession.java

   ..................
   ...................
    ...................
    private Integer bid;  HttpServletRequest request = ServletActionContext.getRequest();  
    private Map<String, Object> session; 
    List<Bookdetails> books = new ArrayList<Bookdetails>();
    private BookdetailsDAO dao = new BookdetailsDAO(); 

    public String execute() 
    {  
           String bookid = request.getParameter("bid");    
        Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
        int checkduplicate=1;

           //getting list from session to compare with the id
        List list = (List) session.get( VisionBooksConstants.USER );  
           Iterator itr = list.iterator(); 
           int bidd=0;

        while(itr.hasNext())
        { 
            Bookdetails bks=(Bookdetails) itr.next();
            bidd=bks.getId(); //getting bookid from arraylist,which was stored in session
            if (bidd==Integer.parseInt(bookid))
            {
           checkduplicate=0; //returns 0 ,so that i can compare it below to avoid duplicate data
         }
        }
         //
        if (book != null && checkduplicate==1  ) 
        { 
            books = sessionBooks();
            HttpServletRequest request = ServletActionContext.getRequest();  
            books.add(book);
            System.out.println("books size"+books.size()); 
        }

        return SUCCESS;
    } 
       ........................
        ...................... 

替代解决方案 HashSet() 更新

  public String execute() 
    {    HashSet<Bookdetails> books = new HashSet<Bookdetails>();
          String bookid = request.getParameter("bid");    
          Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
          books =  (HashSet<Bookdetails>) session.get(BillTransactionBooksConstants.BOK);
          if ( books == null ) books = new HashSet<Bookdetails>();
           boolean already_exists = false; 
            books.add(book);
            System.out.println("books size"+books.size()); 
            session.put(BillTransactionBooksConstants.BOK,books);

        return SUCCESS;
    } 

Bookdetails.java(Pojo)

        package v.esoft.pojos;

    // Generated Nov 5, 2012 9:37:14 PM by Hibernate Tools 3.4.0.CR1

    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import static javax.persistence.GenerationType.IDENTITY;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;


    /**
     * Bookdetails generated by hbm2java
     */
    @Entity
    @Table(name = "bookdetails", catalog = "vbsoftware")
    public class Bookdetails implements java.io.Serializable {

        private Integer id;
        private String isbn;
        private String bookTitile;
        private String authFirstname;
        private String authLastname;
        private String editionYear;
        private Integer subjectId;
        private Integer coverId;
        private Integer languageId;
        private String publisherName;
        private Integer editionId;
        private Float price;
        private String quantity;
        private String description;
        private Integer locationId;
        private String remarks;
        private String img1;
        private String img2;
        private String videoUrl;
        private Integer createrId;
        private Date createdDate;
        private Integer updateId;
        private Date updatedDate;

        public Bookdetails() {
        }

        public Bookdetails(String isbn, String bookTitile, String authFirstname,
                String authLastname, String editionYear, Integer subjectId,
                Integer coverId, Integer languageId, String publisherName,
                Integer editionId, Float price, String quantity,
                String description, Integer locationId, String remarks,
                String img1, String img2, String videoUrl, Integer createrId,
                Date createdDate, Integer updateId, Date updatedDate) {
            this.isbn = isbn;
            this.bookTitile = bookTitile;
            this.authFirstname = authFirstname;
            this.authLastname = authLastname;
            this.editionYear = editionYear;
            this.subjectId = subjectId;
            this.coverId = coverId;
            this.languageId = languageId;
            this.publisherName = publisherName;
            this.editionId = editionId;
            this.price = price;
            this.quantity = quantity;
            this.description = description;
            this.locationId = locationId;
            this.remarks = remarks;
            this.img1 = img1;
            this.img2 = img2;
            this.videoUrl = videoUrl;
            this.createrId = createrId;
            this.createdDate = createdDate;
            this.updateId = updateId;
            this.updatedDate = updatedDate;
        }

        @Id
        @GeneratedValue(strategy = IDENTITY)
        @Column(name = "id", unique = true, nullable = false)
        public Integer getId() {
            return this.id;
        }

        public void setId(Integer id) {
            this.id = id;
        }


        //########################################################################### 
                        //  FOR HASHSETS EQUALS
        //########################################################################### 
        public Bookdetails(int i){ id = i; }

        public boolean equals(Object obj){
            System.err.println("called"); // Never happens
            return id == ((Bookdetails)obj).id;
        }


        @Column(name = "isbn", length = 90)
        public String getIsbn() {
            return this.isbn;
        }

        public void setIsbn(String isbn) {
            this.isbn = isbn;
        }

        @Column(name = "book_titile")
        public String getBookTitile() {
            return this.bookTitile;
        }

        public void setBookTitile(String bookTitile) {
            this.bookTitile = bookTitile;
        }

        @Column(name = "auth_firstname", length = 120)
        public String getAuthFirstname() {
            return this.authFirstname;
        }

        public void setAuthFirstname(String authFirstname) {
            this.authFirstname = authFirstname;
        }

        @Column(name = "auth_lastname", length = 120)
        public String getAuthLastname() {
            return this.authLastname;
        }

        public void setAuthLastname(String authLastname) {
            this.authLastname = authLastname;
        }

        @Column(name = "edition_year", length = 20)
        public String getEditionYear() {
            return this.editionYear;
        }

        public void setEditionYear(String editionYear) {
            this.editionYear = editionYear;
        }

        @Column(name = "subject_id")
        public Integer getSubjectId() {
            return this.subjectId;
        }

        public void setSubjectId(Integer subjectId) {
            this.subjectId = subjectId;
        }

        @Column(name = "cover_id")
        public Integer getCoverId() {
            return this.coverId;
        }

        public void setCoverId(Integer coverId) {
            this.coverId = coverId;
        }

        @Column(name = "language_id")
        public Integer getLanguageId() {
            return this.languageId;
        }

        public void setLanguageId(Integer languageId) {
            this.languageId = languageId;
        }

        @Column(name = "publisher_name", length = 70)
        public String getPublisherName() {
            return this.publisherName;
        }

        public void setPublisherName(String publisherName) {
            this.publisherName = publisherName;
        }

        @Column(name = "edition_id")
        public Integer getEditionId() {
            return this.editionId;
        }

        public void setEditionId(Integer editionId) {
            this.editionId = editionId;
        }

        @Column(name = "price", precision = 12, scale = 0)
        public Float getPrice() {
            return this.price;
        }

        public void setPrice(Float price) {
            this.price = price;
        }

        @Column(name = "quantity", length = 40)
        public String getQuantity() {
            return this.quantity;
        }

        public void setQuantity(String quantity) {
            this.quantity = quantity;
        }

        @Column(name = "description", length = 65535)
        public String getDescription() {
            return this.description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        @Column(name = "location_id")
        public Integer getLocationId() {
            return this.locationId;
        }

        public void setLocationId(Integer locationId) {
            this.locationId = locationId;
        }

        @Column(name = "remarks", length = 65535)
        public String getRemarks() {
            return this.remarks;
        }

        public void setRemarks(String remarks) {
            this.remarks = remarks;
        }

        @Column(name = "img1")
        public String getImg1() {
            return this.img1;
        }

        public void setImg1(String img1) {
            this.img1 = img1;
        }

        @Column(name = "img2")
        public String getImg2() {
            return this.img2;
        }

        public void setImg2(String img2) {
            this.img2 = img2;
        }

        @Column(name = "video_url", length = 65535)
        public String getVideoUrl() {
            return this.videoUrl;
        }

        public void setVideoUrl(String videoUrl) {
            this.videoUrl = videoUrl;
        }

        @Column(name = "creater_id")
        public Integer getCreaterId() {
            return this.createrId;
        }

        public void setCreaterId(Integer createrId) {
            this.createrId = createrId;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "created_date", length = 19)
        public Date getCreatedDate() {
            return this.createdDate;
        }

        public void setCreatedDate(Date createdDate) {
            this.createdDate = createdDate;
        }

        @Column(name = "update_id")
        public Integer getUpdateId() {
            return this.updateId;
        }

        public void setUpdateId(Integer updateId) {
            this.updateId = updateId;
        }

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "updated_date", length = 19)
        public Date getUpdatedDate() {
            return this.updatedDate;
        }

        public void setUpdatedDate(Date updatedDate) {
            this.updatedDate = updatedDate;
        }

    }

【问题讨论】:

  • 只包含相关代码。
  • @DaveNewton 我添加它是因为人们会详细了解我的代码。但现在我删除了。
  • 他们需要帮助的只是确定列表中是否存在重复条目的代码。看起来您真的是在尝试用方式 编写代码——这是基本的Java 内容。对你来说,花一些时间学习一些基本教程而不是问你遇到的每一个问题会更有效率,IMO。

标签: java list struts2 arraylist hashset


【解决方案1】:

如何避免将数据重复插入到我的数组列表中?

改为使用 Set。

另外,请确保您正确实现了 equals 和 hashcode。

【讨论】:

  • 他不应该使用只需要通过 id 比较它们的集合。这意味着 equals 方法将只比较 id 而不是存储在类中的所有其他信息。这通常不是一个好习惯。
  • @AndrejGajduk 问题中没有 equals 方法,因此它检查实例是否相同。这就是为什么我说确保正确实施。您想要一个确保没有重复的数据结构,并且您不想使用集合...?
  • @NimChimpsky 正如您所说,执行此操作的标准方法是什么“这通常不是一个好习惯。” .请告诉我方法,以便我学习新的东西,并从下次开始实施它..
  • @AshutoshSingh stadnard 怎么办?等于和哈希码?整个网站上的大量示例(传递的、反射的、对称的、一致的)。
  • @NimChimpsky 你能用哈希码回答我的问题吗?所以从下一次开始,我将使用哈希码来解决这类问题
【解决方案2】:

已编辑:它现在应该可以工作了。

  public String execute() 
    {  
        String bookid = request.getParameter("bid");    
        Bookdetails book = dao.listBookDetailsById(Integer.parseInt(bookid));
        books = (ArrayList) session.get( VisionBooksConstants.USER );  
        if ( books == null ) books = new ArrayList<Bookdetails>();
        boolean already_exists = false;
        for ( Bookdetails b : books ) {
            if ( b.getID().equals(bookid) ) {
                already_exists = true; break;
            }
        }
        if (book != null && !already_exists  ) 
        { 
            books.add(book);
            System.out.println("books size"+books.size()); 
            session.put(VisionBooksConstants.USER,books);
        }
        return SUCCESS;
    } 

【讨论】:

  • 同样的问题。它不止一次地添加相同的记录。刚才我用完整的代码更新了我的问题。请检查。在您的代码中,您缺少插入 }{ 。而这个if ( books == null ) 没有右大括号或左大括号
  • 对不起,它仍然不止一次添加相同的记录。
  • 您删除了 Bookdetails 类。我会检查方法 b.getID() 是否返回 ID 的字符串表示形式或其他东西(例如整数)。要获取整数的字符串表示形式,请使用如果它是返回的整数,请将if ( b.getID().equals(bookid) ) 部分更改为if ( Integer.toString(b.getID()).equals(bookid))
  • 现在工作正常。我将if ( b.getID().equals(bookid) ) 更改为if ( Integer.toString(b.getID()).equals(bookid))
  • 现在我将尝试使用 Set And Hashcode 解决同样的问题。所以我需要学习 Hashcode 和 Set 以避免将数据重复插入到 arraylist 中。还是别的什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多