-1

i have a class where i am inserting data into a array-list based on the id provided. I am passing a bookId into my class and by comparing bookid i am get a book object. And after getting that object(book) ,am inserting into my arraylist. Now I do't want to insert same data more then once. If a same bookid passes in the class then only it should store once.
i am storing my arraylist into session.

please check my code. And suggest me a solution for my problem.How to avoid duplicate insertion of data into my arraylist?

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;
    } 
       ........................
        ...................... 

Alternative solution HashSet() update

  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;
        }

    }
Dan
  • 2,086
  • 11
  • 71
  • 137
  • Please include *only* the relevant code. – Dave Newton Nov 11 '12 at 11:09
  • @DaveNewton I added it because , people will understand my code in detail way. But now i removed. – Dan Nov 11 '12 at 11:12
  • All they need to help is the code involved in determining if there's a duplicate entry in the list. It really seems like you're trying to write code *way* over your head-this is basic Java stuff. It would be more efficient for you to spend some time with some basic tutorials rather than ask every single question you have, IMO. – Dave Newton Nov 11 '12 at 11:24

2 Answers2

3

How to avoid duplicate insertion of data into my arraylist?

Use a Set instead.

Also, make sure you are implementing equals and hashcode correctly.

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • He shouldn't use a set he needs only to compare them by id. This means that the equals method will be comparing only the ids and not all the other information stored in the class. That is usually not a good practice. – Willem Nov 11 '12 at 10:23
  • @AndrejGajduk There is no equals method in the question, therefore it checks if the instance is the same. Thats why I said make sure to implement correctly. You want a data structure that ensures no duplicates and you don't want to use a set ... ? – NimChimpsky Nov 11 '12 at 10:28
  • @NimChimpsky What is the standard way to do this as you said " That is usually not a good practice." . Please show tell me the way so that i will learn something new and from next time i will implement it.. – Dan Nov 11 '12 at 10:34
  • @AshutoshSingh stadnard way to do what ? equals and hashcode ? loads of examples all over this site ( transistive,reflective,symmetric,consistent ). – NimChimpsky Nov 11 '12 at 10:36
  • @NimChimpsky Can you post a answer for my question using hashcode? So that from next time ,i will use hashcode for this type of problems – Dan Nov 11 '12 at 10:41
  • @AshutoshSingh sorry no. Read about it on this site, think about it and give it a go. Its the best way to learn, then come back with a more specific question if needed. Good luck. – NimChimpsky Nov 11 '12 at 10:42
  • @NimChimpsky Thankyou i read and implemented the HashSet it is very easy and efficient. No need to write extra code for avoid duplicate data. Thanks again. I learn new thing\ – Dan Nov 11 '12 at 14:44
  • @NimChimpsky I tried the same using `Hashsets` after readin a docs. But still it is adding duplicate data. Please chech my code above. – Dan Nov 11 '12 at 16:28
0

EDITED: It should work now.

  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;
    } 
Willem
  • 376
  • 2
  • 8
  • Same problem. It is adding same record more then one time. Just now i updated my question with full code.Please check. And in your code you was missing to insert `}` or `{` . And this `if ( books == null )` have no closing or opening braces – Dan Nov 11 '12 at 10:56
  • sorry, Still it is adding same record more then once. – Dan Nov 11 '12 at 11:29
  • you removed the Bookdetails class. I would check if the method b.getID() - returns String representation of the ID or something else (Integer for example). To get the String representation of an integer use If it is an integer it is returning change the part `if ( b.getID().equals(bookid) )` to `if ( Integer.toString(b.getID()).equals(bookid))` – Willem Nov 11 '12 at 12:04
  • Working fine Now. I changed `if ( b.getID().equals(bookid) )` to `if ( Integer.toString(b.getID()).equals(bookid))` . – Dan Nov 11 '12 at 12:19
  • Now i will try to solve this same issue using Set And Hashcode . So what i need to study Hashcode and Set to avoid duplicate insertion of data into arraylist. Or anything else? – Dan Nov 11 '12 at 12:27
  • You should simply override the equals method on your Bookdetails class. I think there is no big need to implement your own hash function. Then instead of an ArrayList just use a HashSet. With it you don't have to check anything the add method takes care of the duplicate entries. – Willem Nov 11 '12 at 14:22
  • yes.. I got it.I learn new thing. Now i need to remove data from my arraylist by bookId. In similar way as you mention an add method for adding new record into my arraylist(Same code as above). Instead of `books.add(book);` i made `books.remove(book);` but the record is not removing from my arraylist `books`. Just check and let me know why my record is not removing? – Dan Nov 11 '12 at 14:41
  • i also tried to add same method to add book by id using `HashSet` . But it is not working , again it adds dublicate data into my list. Please Check my HashSet update above. – Dan Nov 11 '12 at 16:27
  • Can you post your equals method for the Bookdetails class? – Willem Nov 11 '12 at 16:47
  • Please check **Bookdetails.java(Pojo)** in my above update class. Inside it i written has equals method. – Dan Nov 11 '12 at 17:23
  • change the last line in the equals method to: `return id.equals((Bookdetails)o).id` Are you sure that the equals method never gets called? – Willem Nov 11 '12 at 17:30
  • return id.equals((Bookdetails)o).id); – Willem Nov 11 '12 at 18:14