0

i have the following code, it helps me to delete duplicates elements from the List:

 public static void main(String[] argv)
{

// Créer un objet ArrayList
List<String> array_L = new ArrayList();

// Ajout des éléments avec doublon
array_L.add("Londre");
array_L.add("Paris");
array_L.add("New York");
array_L.add("Londre");
array_L.add("Paris");
array_L.add("Londre");

System.out.println ("Contenu avec doublon: "+array_L);

// Créer une liste de contenu unique basée sur les éléments de ArrayList
Set<String> mySet = new HashSet<String>(array_L);

// Créer une Nouvelle ArrayList à partir de Set
List<String> array_L2 = new ArrayList<String>(mySet);

// Afficher le contenu de ArrayList
System.out.println("Contenu sans doublon: "+mySet);
  }

then im trying to move a little forward, and to create a List of objects(Book for example):

    public static void main(String[] argv)
{

// Créer un objet ArrayList
List<Book> array_L = new ArrayList<Book>();

// Ajout des éléments avec doublon
Book b=new Book();
b.setName("Londre");
b.setSbn(123);

Book b2=new Book();
b2.setName("Paris");
b2.setSbn(1);

Book b3=new Book();
b3.setName("Londre");
b3.setSbn(123);
array_L.add(b);
array_L.add(b2);
array_L.add(b3);

System.out.println ("Contenu avec doublon: "+array_L);

// Créer une liste de contenu unique basée sur les éléments de ArrayList
Set<Book> mySet = new HashSet<Book>(array_L);



// Afficher le contenu de ArrayList
System.out.println("Contenu sans doublon: "+mySet);
 }

the Book Object

public class Book {
String name;
 int sbn;

  //getters and setters
}

so at the end it's keeps all the data, including the duplicates one

John specter
  • 161
  • 14

2 Answers2

0

You are using a Set to eliminate duplicates from a List. So far, so good.

The problem is that the constructor of HashSet has no way to find out if 2 Books are the same.

Let your IDE generate the methods equals and hashCode in the class Book to fix this behaviour.

f1sh
  • 11,489
  • 3
  • 25
  • 51
0

In your case, you are adding different objects(which are not located on same memory location because of create using 'new' keyword.)

so, far it becomes unique then each other, to fix it.

You need to decorate your Book Class into following manner,

class Book {
    private String name;
    private int sbn;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getSbn() {
        return sbn;
    }

    public void setSbn(int sbn) {
        this.sbn = sbn;
    }

    @Override
    public int hashCode() {
        return this.getSbn();
    }

    @Override
    public boolean equals(Object obj) {
        Book b1 = (Book) obj;
        if (b1.getName().equals(this.getName())) {
            return true;
        }
        return false;
    }

}
Vishal Gajera
  • 4,137
  • 5
  • 28
  • 55