Java Method for removing duplicates from char array

后端 未结 5 1213
礼貌的吻别
礼貌的吻别 2021-01-24 01:40

I have a char array filled by the user (arrayInput[]) with some characters, like {b, d, a, b, f, a, g, a, a, f}, and I need to create a method which returns a new c

5条回答
  •  爱一瞬间的悲伤
    2021-01-24 02:37

    If you consider using of collection framework then it would be much easier. Your array of char with duplicate is arrayInput. Now put each char from it to a HashSet like this -

    HashSet uniqueCharSet = new HashSet();
    for(char each : arrayInput){
    
       uniqueCharSet.add(each);
    }   
    

    Now the HashSet uniqueCharSet will contains only the unique characters from the char array arrayInput. Note here all element in uniqueCharSet are wrapper type - Character.

    You can convert the HashSet uniqueCharSet to array of Character like this -

    Object[] uniqueCharArray = uniqueCharSet.toArray();
    

    And then you can use them like this -

    for(Object each : uniqueCharArray){
       Character c = (Character) each;
       System.out.println(c);
    }
    

提交回复
热议问题