开发者

How do i remove an array entry in java(be simplistic please?) [duplicate]

开发者 https://www.devze.com 2023-02-04 13:51 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: How do I remove objects from an Array in java?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How do I remove objects from an Array in java?

Basicly, this is my code(a Adress book) i used an arrow to point out the bits of code that are about the remove array(So far) i just need some dire help, im a school student and help would be lovely....

Edit 1; Sorry im new to the site, my problem is, i need to remove an entry from an array, this is my remove method. I have a search method(works fine) its just my rem开发者_高级运维oving protocol does not work, What i want to do is remove the chosen entry(name[],homeNum[],cellNum[],) which is those 3 array, and im using the clone of those arrays, to delete it, and i need it in a shorter array(0-3, instead of 0-4), nothing fancy, i just need some collective critism, and i know nothing of java lists....

/*---->*/ public static void Remv(String cloneName[],String cloneHomeNum[],String cloneCellNum[]){
    int k=0,x;
    String username="";
    String name[]=new String[5];
    String homeNum[]=new String[5];
    String cellNum[]=new String[5];
    x=Searching(name,username);
    for(int j=0;j<5;j++){
        if(j!=x){
            cloneName[j]=name[j];
            cloneHomeNum[j]=homeNum[j];
            cloneCellNum[j]=cellNum[j];
            k=k+1;
        }else if(j==x)
        cloneName[k]=name[j];
        cloneHomeNum[k]=homeNum[j];
        cloneCellNum[k]=cellNum[j];


    }
 }
}


I think that you should start by understanding how does the array collection works, and knowing what is what you are trying to accomplish.

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

E.g. The following array:

String[] name = new String[5];

would have space for 5 strings, and you can't remove any of those spaces, what you can do is assign a null value to any of them.

So if what you want is to remove the value you can simply do name[2] = null; If what you want is to remove the value and the space containing it, you need to use the little 'trick' indicated in Octopus-Paul Answer.

    List<String> list = new ArrayList<String>(Arrays.asList(array));
    list.removeAll('a');
    array= list.toArray(array);

a) if you want to remove all instances of 'a'.

list.removeAll('a');

b) if you want to remove the first ocurrence of 'a'.

list.remove('a');

c) if you want to remove the value at a specific index.

list.Remove(2)

Regards.

0

精彩评论

暂无评论...
验证码 换一张
取 消