java - Unique classes in generic list -


i have generic class generic list in it. want ensure generic list contains unique classes.

have done far compare class names reflection (getclass()). think that's not clean solution. there better practices check?

public class mygenericclass<t extends mygenericclass.myinterface> {   private list<t> members = new arraylist<>(0);    public void add(t t) {     final boolean[] classinmembers = {false};      members.foreach(member -> {       if (member.getclass().getname().equals(t.getclass().getname())) {         classinmembers[0] = true;       }     });      if (!classinmembers[0]) {       members.add(t);     }   }    public interface myinterface {     void dosomething(string text);   } } 
public class main {   public static void main(string[] args) {     mygenericclass<mygenericclass.myinterface> mygenericclass = new mygenericclass<>();      mygenericclass.add(new performer1());     mygenericclass.add(new performer2());     mygenericclass.add(new performer3());     mygenericclass.add(new performer3()); // should not inserted!   }    private static class performer1 implements mygenericclass.myinterface {     @override     public void dosomething(string text) {       text = "hi, performer 1!";     }   }    private static class performer2 implements mygenericclass.myinterface {     @override     public void dosomething(string text) {       text = "hi, performer 2!";     }   }    private static class performer3 implements mygenericclass.myinterface {     @override     public void dosomething(string text) {       text = "hi, performer 3!";     }   } } 

you subclass java.util.set interface implementation. easiest subclass java.util.abstractset.

by default 'set' compare objects .equals() method - in case, not sufficient. need override contains method ensure instances of unique class added.

in overrideen contains, it's same / easier compare class instances rather stringified package name

i.e. use a.getclass() == b.getclass(), rather a.getclass().getname()


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -