Duplicate elements - TreeSet

I've got the following user-defined class:
class User{
     public String name = null;
     public String add = null;
     public String getName(){     
          return name;
     public String getAdd(){
          return add;
     public void setName(String name){
          this.name = name;
     public void setAdd(String add){
          this.add = add;
public static void main(String args[]){
          User u1 = new User();
          User u2 = new User();
          u1.setName("A");
          u2.setName("A");
          u1.setAdd("A");
          u2.setAdd("B");
          TreeSet ts = new TreeSet();
          System.out.println(ts.add(u1));
// This line throws classcastexception
          System.out.println(ts.add(u2));
I need to add the objects of this class in a set so the duplicate objects are eliminated. The above code when run throws classcastexception.
Is there any workaround.Pls help me.
Thanks.

In addition to what the others have said, I would suggest overriding equals and hashCode. I don't think it's strictly necessary for putting things in a TreeSet, but it's probably a good idea, especially if you go the Coparable router (as opposed to Comparator).
Here's some stuff you may find useful:
Making Java Objects Comparable
http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html
http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf

Similar Messages

  • HOW TO DELETE DUPLICATE ELEMENT IN A VECTOR

    Hi everybody!
    If I've a vector like this vectA={apple,orange,grape,apple,apple,banana}
    and I want final result be vectB={apple,orange,grape,banana}.
    How should I compare each element in vectA and delete duplicate element. Like here duplicated element is apple. Only one apple remain in the vectB.
    Any help,
    Thanks.

    Hello all. Good question and good answers, but I would like to elaborate.
    To begin with, you specifically asked to map the following:
    {apple,orange,grape,apple,apple,banana} ==> {apple,orange,grape,banana}
    Both of cotton.m's solutions do NOT do this, unfortunately. They are both useful in particular cases though, so think about what you're trying to do:
    cotton.m's first solution is best if order does not matter. In fact, as flounder first stated, whenever order doesn't matter, your most efficient bet is to use a Set instead of a List (or Vector) anyways.
    Set vectB = new HashSet(vectA);This code maps to {banana, orange, grape, apple}, because HashSets are "randomly" ordered.
    cotton.m's second solution is good if you want to impose NEW ordering on the List.
    Set vectB = new TreeSet(vectA);This code maps to {apple, banana, grape, orange}, because TreeSet uses alphabetical-order on Strings by default.
    java_2006, your solution is the most correct, but it's a little verbose for my taste :)
    more importantly, the runtime-efficiency is pretty bad (n-squared). calling Vector.contains performs (at worst) n comparisons; you're going to call it n times! Set.contains usually performs 2 comparisons (constant, much better), so I suggest you USE a Set to do the filtering, while still sticking with your good idea to use a List. When the ordering is "arbitrary" (so can't use TreeSet) but still relevant (so can't use HashSet), you're basically talking about a List.
    I think saving A LOT of time is worth using A LITTLE extra space, so here, let's save ourself some runtime, and some carpal-tunnel.
    import java.util.*;
    class Foo {
         public static void main(String[] args) {
              String[] fruits = {"apple","orange","grape","apple","apple","banana"};
              List     l = Arrays.asList(fruits),
                   m = filterDups(l);
              System.out.println(m);
         // remember, both of the following methods use O(n) space, but only O(n) time
         static List filterDups(List l) {
              List retVal = new ArrayList();
              Set s = new HashSet();
              for (Object o : l)
                   if (s.add(o))
                        retVal.add(o);     // Set.add returns true iff the item was NOT already present
              return retVal;
         static void killDups(List l) {
              Set s = new HashSet();
              for (Iterator i = l.iterator(); i.hasNext(); )
                   if (! s.add(i.next()))     
                        i.remove();
         // honestly, please don't use Vectors ever again... thanks!
         // if you're going to be a jerk about it, and claim you NEED a Vector result
         // then here's your code, whiner
         public static void mainx(String[] args) {
              String[] fruits = {"apple","orange","grape","apple","apple","banana"};
              List l = Arrays.asList(fruits);
              Vector v = new Vector(l);
              killDups(v);
              System.out.println(v);
    }

  • Error: duplicate element "AddressOnParent"

    Hi,
    I'm trying to open an ANM OVA file: "anm-va-5.2.2.ova" on a ESXi server version 5.1 with vCenter 5.1.
    I'm getting the following Error -" line 79:duplicate element 'AdderssOnParent' ".
    Can someone help figure out how can i open this OVA file?
    I attached the Error message  i get.
    thanks.

    I ran into this problem, too.
    Jonatan, the only issue with running this on ESXi 5.1 that I've found is that the .ova contains some incorrect language for the newer release (disk definitions are incorrect).
    If you extract the .vmdk from the .ova file and build a new machine with the correct ram, CPU etc and choose to 'use existing vmdk' when setting up the appliance, you should find that it boots right up and starts working
    I've got that running in my environment quite happily.

  • Handling duplicate element names

    Hi,
    I have been stuck with duplicate element name in my XML. Below is the skeleton of it...
    <Admin>
    <Information>
    <Company>
    <CompanyName>Apple</CompanyName>
    <CompanyCode>APP</CompanyCode>
    </Company>
    <TNumber>1-1-123456</TNumber>
    <RefrenceNumber>DA1101</RefrenceNumber>
    </Information>
    <Lists>
    <ListItem>
    <PolicyNumber>A100</PolicyNumber>
    <ListType OWNER="true" HOLDER="true">
    <CoverageValue>100</CoverageValue>
    </ListItem>
    <ListItem>
    <PolicyNumber>A200</PolicyNumber>
    <ListType OWNER="false" HOLDER="false">
    <CoverageValue>200</CoverageValue>
    </ListItem>
    <ListItem>
    <PolicyNumber>A300</PolicyNumber>
    <ListType OWNER="true" HOLDER="true">
    <CoverageValue>300</CoverageValue>
    </ListItem>
    </Lists>
    </Admin>
    The final Output list of Columns I will need are TNumber, ListTypeOwner,ListTypeHolder,CoverageValue
    I loaded few XMLs into my XMLType table XML_SAMPLE
    Below is the query i use... But every time I try i get no records. I do a sample query without reading the Tnumber I am able to read the values for the 2 XMLs. But when I do a extract for TNumber and the elements inside the ListItem I am not getting back anything.
    Below is my query
    select m.TNumber,l.ListTypeHolder,l.ListTypeOwner,l.CoverageValue
    from XML_SAMPLE,
    xmltable(
    xmlnamespaces(DEFAULT 'http://www.xxx.com/Pway/Workfile')
    '$XS/Admin' passing object_value as "XS"
    columns
    TNumber VARCHAR2(255) PATH '/Admin/Information/TNumber',
    Item_Fragment XMLTYPE PATH 'Lists/ListItem'
    ) m,
    xmltable(
    xmlnamespaces(DEFAULT 'http://www.xxx.com/Pway/Workfile')
    '$LI/ListItem' passing m.Item_Fragment as "LI"
    columns
    ListTypeHolder VARCHAR(255) PATH 'ListType/@HOLDER',
    ListTypeOwner VARCHAR(255) PATH 'ListType/@OWNER',
    CoverageValue VARCHAR(255) PATH 'CoverageValue'
    ) l
    where l.ListTypeOwner="false";
    I know its something to do the way the root tag or something. But i have tried out my options Please correct where I am making a mistake

    Works for me, after correcting a few sytntax errors and wellformedness issue :
    SQL> select m.TNumber,l.ListTypeHolder,l.ListTypeOwner,l.CoverageValue
      2  from XML_SAMPLE
      3     , xmltable(
      4         xmlnamespaces(DEFAULT 'http://www.xxx.com/Pway/Workfile')
      5       , '$XS/Admin' passing object_value as "XS"
      6         columns
      7           TNumber VARCHAR2(255) PATH 'Information/TNumber',
      8           Item_Fragment XMLTYPE PATH 'Lists/ListItem'
      9       ) m
    10     , xmltable(
    11         xmlnamespaces(DEFAULT 'http://www.xxx.com/Pway/Workfile')
    12       , '$LI/ListItem' passing m.Item_Fragment as "LI"
    13         columns
    14           ListTypeHolder VARCHAR(255) PATH 'ListType/@HOLDER',
    15           ListTypeOwner VARCHAR(255) PATH 'ListType/@OWNER',
    16           CoverageValue VARCHAR(255) PATH 'CoverageValue'
    17       ) l
    18  --where l.ListTypeOwner = 'false'
    19  ;
    TNUMBER            LISTTYPEHOLDER     LISTTYPEOWNER    COVERAGEVALUE
    1-1-123456         true               true             100
    1-1-123456         false              false            200
    1-1-123456         true               true             300
    (tested on 11.2.0.3)

  • Ho to remove duplicate element in the List ?

    It seem to be very basic, but it not working, even I try different way.
    This my List [10, 10, 11, 11, 12, 12, 13, 13, 14, 14],
    now to remove duplicate elements to have at the end [10, 11, 12, 13, 14]
    my code seem to be perfect but...
    for(int i = 0; i < listA.size(); i++){
         if(i%2 == 0){
              System.out.println("ce i est un nombre pair "+i);
              listA.remove(i);
    System.out.println(listA);

    senore100 wrote:
    The problem is that every single time an element is removed, the whole ArrayList is re-shuffled, with all the elements to the right moved to the left on spot. That's why.Yes, that's right. However if you had used an Iterator over the list, you could easily have removed every other element. It's only when you use an array index that you run into this (very common) problem.

  • Duplicate element names

    hi all
    in uk hrms manager resposnibility  there is total compensation--element
    here i created a flexfield named arabic name and then to the already existing elements the user added arabic names
    now the prompt for update or correction appears and i clicked update
    as a result duplicate entries for the same element are coming in all the reports eg. an element named Personal loan recovery comes twice
    earlier in the element screen the effective date was coming as 1-jan-1990 ,Now its coming as 28-dec-2011
    should i have clicked correction?is there any way to undo what i did ?
    kindly guide me
    thanking in advanceEdited by: makdutakdu on Dec 29, 2011 7:11 AM

    hi
    thank you very much for your reply
    i did a delete next
    let me just summarise what i did
    eg Kuwaiti sick leave
    after doing an update there r two entries in per_element_types_f
    ELEMENT_TYPE_ID     EFFECTIVE_START_DATE     EFFECTIVE_END_DATE     BUSINESS_GROUP_ID     LEGISLATION_CODE     FORMULA_ID
    106     01/01/1990     12/29/2011     0.00     NULL     215
    106     12/30/2011     12/31/4712     0.00     NULL     215
    now i go to front end
    click on effective_date_from go to tools--alter effective_date give a precious date eg if it is 28 dec give 27 dec
    then click on the 2nd effective_date and go to edit --delete choose the option with next
    then click save
    requery the element once more
    and check in petf table
    ELEMENT_TYPE_ID     EFFECTIVE_START_DATE     EFFECTIVE_END_DATE     BUSINESS_GROUP_ID     LEGISLATION_CODE     FORMULA_ID
    106     01/01/1990     12/31/4712     0.00     NULL     215
    just one entry
    i learnt a new thing via a mistake
    thanks clive and vigneshwar for the guidance and patience,i wish there was an option to mark correct twice
    hope this will help ppl like who do an update instead of doing correction
    Edited by: makdutakdu on Jan 4, 2012 1:20 PM

  • VI Scripting: get reference of the duplicate element

    In VI scripting I copy element (any type of indicator, control, constant) with Move method with duplicate property - true. The output top right terminal of the method is the reference to the source object, not the new one.
    Is there any straightforward way to get reference to that copy (other copy method, etc)?
    Not straightforward solutions (they may work on test examples, but not good)
    1) move to temporary cluster - easy to find a new element
    2) list all objects before, after and compare lists. But the source VI can be of any size and complexity.
    3) Create element copy manually - bad, the solution should work on all kinds of elements.
    Solved!
    Go to Solution.

    Good method.
    It is almost working!
    It can create controls and indicators, but fails with constants (Class conflict, when wiring constant reference to the Source Object Reference terminal)
    Besides, there is a wrong description of the method (LV 2011):
    LabVIEW help
    Create from reference method:
    Source Object Reference
    A reference to the object you want to duplicate on the target VI. If you use this parameter, you do not need to wire the _type descriptor and style fields_.
    There are no type descriptor and style fields at all, they are in other methods
    Who is failing, me or LV? =)
    Attachments:
    Duplicate constant fails.png ‏56 KB

  • "Results By Calendar Group" Accumulator return duplicate elements

    i hv spend whole day debuging the following panel
    Nav: GP > Absence & Payroll Processing > Review Absence/Payroll Info > Results by Calendar Group > Accumulator tab
    screenshot http://img716.imageshack.us/img716/7603/216.jpg
    element for "Extended maternity leave" are duplicate 3 to 4 times.
    I am not sure which config goes wrong...
    Can some guru help?
    Really thanks

    Below are the optimizer db parameter settings:
    SQL> show parameter optimizer
    NAME                                 TYPE        VALUE
    _optimizer_push_pred_cost_based      boolean     FALSE
    optimizer_dynamic_sampling           integer     2
    optimizer_features_enable            string      10.2.0.1
    optimizer_index_caching              integer     0
    optimizer_index_cost_adj             integer     100
    optimizer_mode                       string      ALL_ROWS
    optimizer_secure_view_merging        boolean     TRUE

  • How to removie a duplicate element of array

    i have this code so far can someone please help
    public static int [] remove(int[] a, int[] b){
    for(int i = 0; i < a.length; i++) {
    if(a[i] == b) {
    int[] newInt = new int[a.length - 1];
    return newInt; // We need something here
    return a;

    First, please use [ code] and [ code] tags to denote code; it makes it much more readable.
    Second, your arguments for the function don't make sense with relation to your subject. So, running on the asumption that I know what you mean through the subject, here goes:
    You probably want the arguments to be:
    (int[] a, int b)Whereby you want to remove the element that equals b . So, what you would want to do in such a situation is:
    for(i = 0 to a.length) {
    if(a[i] == b) {
      //You have reached the element to throw away.  Set a flag saying you have reached this point
    // If the flag is set, add a[i+1] to the new array; otherwise add a[i] to the new array.
    return a;

  • Delete duplicate xml element message

    If I coincidently insert into xml type, with duplicate element as below. How would I remove it?
    The duplicate element here is <lastname>
    Thanks for your help,
    Luan
    --- I used this code from example of other forums.
    create table XML_CLOB of XMLType;
    prompt 'insert into XML_CLOB values ( xmltype(<student id="211"><personal idPer="2561"><firstName>John</firstName><middleName>Michael</middleName><lastName>Scott</lastName><birthday>15-11-1984</birthday><address>8600 Beverly Blvd.</address><city>Los Angeles, CA.</city><country>USA</country></personal></student>))';
    insert into XML_CLOB values ( xmltype(
    '<student id="211">
    <personal idPer="2561">
    <firstName>John</firstName>
    <middleName>Michael</middleName>
    <lastName>Scott</lastName>
    <lastName>Scott</lastName>
    <birthday>15-11-1984</birthday>
    <address>8600 Beverly Blvd.</address>
    <city>Los Angeles, CA.</city>
    <country>USA</country>
    </personal>
    </student>'));

    Using your first sample.
    You can count the number of lastName nodes explicitly :
    SELECT XMLQuery(
    'count(/student/personal/lastName)'
    passing object_value
    returning content
    ).getNumberVal() as node_count
    FROM xml_clob
    WHERE existsNode(object_value, '/student[@id="211"]') = 1
    ;or count occurrences of each node, student-wise :
    SQL> SELECT extractvalue(t.object_value,'/student/@id') as student_id,
      2         x.node_name,
      3         count(*)
      4  FROM xml_clob t,
      5   XMLTable(
      6    'for $i in /student/personal/*
      7     return local-name($i)'
      8    passing t.object_value
      9    columns
    10     node_name  varchar2(30) path '.',
    11     posn       for ordinality
    12   ) x
    13  WHERE existsNode(t.object_value, '/student[@id="211"]') = 1
    14  GROUP BY extractvalue(t.object_value,'/student/@id'), x.node_name
    15  ;
    STUDENT_ID                                    NODE_NAME                        COUNT(*)
    211                                           birthday                                1
    211                                           middleName                              1
    211                                           address                                 1
    211                                           lastName                                2
    211                                           firstName                               1
    211                                           country                                 1
    211                                           city                                    1
    7 rows selected
    I wanted to delete the duplicate of <personal idPer="2561">OK, using your second sample, still with deleteXML function :
    UPDATE xml_clob
    SET object_value = deleteXML(object_value, '/student/personal[@idPer=preceding-sibling::personal/@idPer]')
    WHERE existsNode(object_value, '/student[@id="211"]') = 1;It will delete duplicate personal nodes (based on attribute idPer).
    Here, the XPath expression "/student/personal[@idPer=preceding-sibling::personal/@idPer]" selects every personal node having an idPer existing in a previous personal node.

  • Duplicate Global Element

    Hi All,
    I have a little problem (Weblogic portal 10.2) with duplicate elements in wsdl files. I have two wsdl files for two different webservices. Both the wsdl files use the same xsd (import in wsdl file) and both wsdl files have an element declaration with the same name. This seems legal to me but I see "Duplicate global element" errors in my problem section. Is there a way to solve this problem? It should be possible to have two wsdl files with the samen element declaration, or not?
    Thanks!

    make sure to have different target namespaces set for the wsdls

  • Check duplicate record in array

    suppose i have an array
    int a[]={1,2,3,4,4,5,6,7,7};
    how should i check duplicate record and remove them?
    thanks...

    Write yourself some pseudo-code:
    // Loop though all the elements in the array from 0 to length-2.
    // For each element i, loop through following elements from i+1 to length-1
    // if the following element is equal to the current one, do something with it.
    "do something" can mean either one of two things:
    (1) Remove it (VERY messy) or
    (2) Create a new array and only add in the non-duplicate elements.
    The easiest thing of all would be to create a List and then create a Set from that. Why code all this logic when somebody has already done it for you? Look at the java.util.Arrays and java.util.Collections classes. Use what's been given to you.
    %

  • About Duplicate entries

    Hi experts,
    In internal table i have many account numbers.
    There are some duplicate entries. i have removed all the duplicates using the following code.
    but i cannot remove all the duplicate entries.
    certain scenarios i should have duplicate elements also in my output.
    certain scenario i should remove the duplicates.
    is there any way to remove few duplicate entries from internal table.
    your furthur clarification i will send the code also.
    DELETE ADJACENT DUPLICATES FROM itab_temp COMPARING RI_ACCT_NO .
      LOOP AT ITAB_temp.
      LOOP AT ITAB WHERE RI_ACCT_NO = ITAB_TEMP-RI_ACCT_NO.
        SUM_BETRH = SUM_BETRH + itab-BETRH.
        SUM_BETRW = SUM_BETRW + itab-BETRW.
    ENDLOOP.
        ITAB_ALS = ITAB.
        ITAB_ALS-BETRH = SUM_BETRH.
        ITAB_ALS-BETRW = SUM_BETRW.
          APPEND ITAB_ALS.
        CLEAR: SUM_BETRH, SUM_BETRW, ITAB_ALS.
      ENDLOOP.
    if u know pls send me documents to
    [email protected]
    its very urgent.
    Thank you in advance.
    Jeyanthi

    Hi
    You have add the following statement before the delete duplicate statement
    SORT itab_temp BY RI_ACCT_NO.
    DELETE ADJACENT DUPLICATES FROM itab_temp COMPARING RI_ACCT_NO .
    I think now it will work. Otherwise some problem internal table fields.
    Moreover this code not efficient.  You are using nested loops, it is performance killer.  Instead you can use for all entries.  Already u have data in ITAB_TEMP.
    Select f1 f2... from XTABLE into table ITAB for all entries in ITAB_TEMP where RI_ACCT_NO = ITAB_TEMP-RI_ACCT_NO .
    then u can add addition logic by using one loop and endloop.
    Reward me if it is useful

  • Global delete duplicates in PSE 12 Mac

    Is there a way to do large deletes of multiple files in PSE 12 Mac?  I have 1000s of duplicate files, and can't review each of them.  It should be possible by specifying exactly duplicates, no?

    Locana a écrit:
    Is there a way to do large deletes of multiple files in PSE 12 Mac?  I have 1000s of duplicate files, and can't review each of them.  It should be possible by specifying exactly duplicates, no?
    The sad truth is : No.
    The main problem is that even assuming the program is able to find duplicates candidates, it can't choose which to delete.
    10 thoughts about duplicates - Elements Village
    So, your hope is to find duplicates, not individually, but hopefully by all folders (which is a common situation).
    The main thing to understand is that for the organizer, duplicates are files with the same 'date taken' and size in kB. On the other hand, the tools offered by the organizer to find duplicates are based on 'visual similarity'.

  • Question about TreeSet

    Hi,
    I'm currently implementing an algorithm where I need an ordered data structure with O(log n) for searching, adding and removing. Therefore, TreeSet sounds perfect. However, I also need sometimes to get, given an element on the TreeSet, the previous and next elements, assuming that they exist.
    I obviously want those operations to be logarithmic too. I've tried using mySet.headSet().first() and mySet.tailSet().last(), because I've read somewhere that the tailSet and headSet operations are logarithmic, since they represent a view of the part, not a copy of it.
    However, I'm not sure of this and therefore I would like to know if there's a better way of implementing previousTo and nextTo (as I call them).
    Thanks in advance.

    I've tried using mySet.headSet().first() and
    mySet.tailSet().last(), because I've read somewhere
    that the tailSet and headSet operations are
    logarithmic, since they represent a view of thepart,
    not a copy of it.I don't understand how you get that to work. To get
    the previous element I had to call headSet and then
    last. To get the next element I had to call tailSet,
    take out an iterator and then step forward two
    elements,
    TreeSet ts = new TreeSet();
    ts.add(new String("1"));
    ts.add(new String("5"));
    ts.add(new String("3"));
    ts.add(new String("4"));
    ts.add(new String("2"));
    System.out.println(ts.headSet(new
    String("3")).last());
    Iterator it = ts.tailSet(new String("3")).iterator();
    it.next();
    System.out.println(it.next());The above TreeSet holds 1,2,3,4,5. The code snippet
    prints 2 and 4. Those are the elements before and
    after 3.Sorry, sorry, I screwed up when writing. I meant headSet.last and tailSet.first, exactly like you did. It works, but the problem is that the TreeSet javadoc doesn't say anything about headSet and tailSet 's complexity. I have the impression that it could be O(n) on a worst case.

Maybe you are looking for

  • Need Help to query Lync Database for User Information

    Need Help to Query the lync database to retrieve below user information. 1. SIP Address of the registered user         2. Phone Number configured to the particular account.         3. IP Address        4. Last Logged in time. I am trying to pull the

  • OO class and events program

    Hi All, I am not an experienced ABAP OO programmer. Here is the requirement. I need to develop an ABAP OO program which has to send an SMTP mail for all exceptions. The exceptions need to be handled using event handling functionality inside try catch

  • Request for little enhancement in APEX 3.0

    At definition page it would be nice to see if a region is conditional or not. Thanks

  • Satellite Pro L300 - How to transfert Windows on new HDD?

    Hello, I recently got an hard drive from a broken laptop bigger than mine. I would like to put it in my computer, but I don't know what would be the way to transfer the installation partition (or even better also the windows already installed partiti

  • Apple mail issues!

    In mail i keep getting red flagged mail that i can't trash, please help!