How can I remove duplicate elements from a given array in java without using collections

后端 未结 10 751
逝去的感伤
逝去的感伤 2021-01-06 02:20

I have an array elements like this:

int arr[] = {1,1,2,2,3,3,4,4};

I want to remove the duplicate elements from. Searched on the internet

10条回答
  •  清酒与你
    2021-01-06 03:17

    package com.array;
    import java.util.*;
    
    class RemoveDuplicatesInArray{
    
        public static void main(String[] args) {
            Integer[] array = new Integer[10];
    
            array[0] = 1;
            array[1] = 2;
            array[2] = 3;
            array[3] = 3;
            array[4] = 3;
            array[5] = 3;
            array[6] = 7;
            array[7] = 7;
            array[8] = 9;
            array[9] = 9;
            removeDuplicatesFromArray(array);
    
        }
    
    
        private static void removeDuplicatesFromArray(Integer[] array){
            StringBuffer stringBuffer = new StringBuffer();
             String arrayString =  Arrays.toString(array);
             for(int index =0 ; index <= arrayString.length(); index++){
              try{
                  int number = Integer.parseInt(arrayString.charAt(index)+"");
                  if(!stringBuffer.toString().contains(number+"")){
                  if(stringBuffer.length()!=0)
                      stringBuffer.append(",");
                     stringBuffer.append(number);
                  }
    
              }catch(Exception e){
    
              }
             }
             String[] stringArray = stringBuffer.toString().split(",");
             array = new Integer[stringArray.length];
             for(int index = 0 ; index < stringArray.length ; index++){
               array[index] = Integer.parseInt(stringArray[index]); 
             }
             System.out.println(Arrays.toString(array));
          }
    
    }
    

提交回复
热议问题