Java - removing object from Array -
I need to make a method to remove an element from an array of objects, without any archeists.
This is the constructor for my object:
public person (string name 1, string tello1) {name = name1; TELO = TELO 1; } and my array:
int capacity = 100; Private person [] thePhonebook = new person [capacity]; And I have a shell for my removal method:
Delete public string {enter the name} {// name} Name (Do not worry about duplicate names) // Returns the telephone number of the deleted entry} I do not know how to delete the element in the array (I tap I want to clear it now)
I have a couple of elements to create a new array Not on creating a new array and consider the removal of parts of copying, but I'm not sure how to implement it.
I also have a method of finding that can be used to find the name of a person who is helpful:
Private int search (string Name) {String name1 = name; Int i = 0; Int element = 0; Int found = 0; While (i & lt; size) {if (phonebook [i] .getName (.) Equals (name1)) {elementNo = i; Found = 1; break; }} If (found == 1) {return dirNo; } Else {dirNo = -1; Return Dino; }} Thank you for your time.
You can not directly remove the element from an array in Java You have two options: < p> If you need to preserve the order of elements in the array: Start with the index that you want to delete, and make each element "down" to an index (index 0). , Such as: Delete public string (string name) {string result = zero; Int index = search (name); If (index> = 0) {result = the bookbook [index] .telno; (IntitI = Index + 1; I & lt; The Phonebook; Lang; ++ I) {Phonebook [I - 1] = The Phonebook [I]; If (phonebook [i] == empty) {break; }} Phonebook [the phonebook.length - 1] = Faucet; } Return results; } In the above implementation, the value in the array is the symbol of the end of the null list. B. If the sequence of elements of the array does not matter: Swap the element that you want to remove from the last element of the list. Note that in order to do this you need to maintain a length value for the list, which is the value the PhonebookLength in the code below. public string removal industry (string name) {string result = null; Int index = search (name); If (index> = 0) {result = the bookbook [index] .telno; Phonebook [index] = Phonebook [Phonebook Lang - 1]; Phonebook [- thePhonebookLength] = Faucet; } Return results; } One of the benefits of both of these solutions is that the array is modified in in place , without the use of allocation. After presenting these possibilities, I suggest that using archive is better for your purposes - such as list of subclasses One or more commonly seen by the name of map are normal.
Comments
Post a Comment