Jump to content

deleting an element

- - - - -

  • Please log in to reply
3 replies to this topic

#1
speachy_15

speachy_15

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts
hello again... i've been stuck in this problem earlier....

how can you delete an element in an array and then print the array minus the deleted item???
thank you!!!








*i'm really just a noob here.... all i can do now are simple programs....*sigh*

#2
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
You could:
1 - Use a List
2 - Use a second array of booleans, the same size as the other array, that tells you for every element if it's "deleted" or not.
For example:

int [] array = new int[10];
boolean [] controlArray = new boolean[10];

...

private void deleteElement(int elementPosition){
    controlArray[elementPosition]=false;
}

...

private void printArray(){
   for(int i=0;i<10;i++){
      if(controlArray[i])
         System.out.print(array[i]+" ");
   }

}



#3
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
private int[] array = new int[10];
...
...
private void removeElement(int index){
  int[] tempArray = new int[array.length];
  int counter;
  for(int i=0 ; i<array.length ; i++){
    if(index != i){
      tempArray[counter++] = array[i];
    }
  }

  array = tempArray;
}

public void print(){
  for(int i=0 ; i<array.lenghth ; i++){
    System.out.print(array[i] + " ");
  }
}


#4
eafkuor

eafkuor

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 218 posts
That's another way to go!
Or you could use System.arrayCopy to implement the code oxano posted. It should be faster.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users