aspose file tools*
The moose likes Beginning Java and the fly likes adding and removing items from an array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "adding and removing items from an array" Watch "adding and removing items from an array" New topic
Author

adding and removing items from an array

brent carter
Ranch Hand

Joined: Dec 15, 2011
Posts: 34
hi guys. I have an array item[] with 5 strings in it. I want to have it so if a person inputs one of the strings, java recogize that the input belongs in that array and removes it. (something like, if input = arrayitem, array = array - input). Can anyone point me in the right direction?
Swapnil Sanghai
Ranch Hand

Joined: Dec 05, 2011
Posts: 41

Do this
check the entered String object with that of in your array's every item. If match is true then replace it with blank space.
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10451
    
    8

You can either set it to null or create a new array with that particular string removed.
I personally would prefer using a List instead of an array*
*Check out the Arrays class for a method which will create and return a List from your array


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
brent carter
Ranch Hand

Joined: Dec 15, 2011
Posts: 34
thanks guys, you both sent me on the right path. However, when i set it to null it prints out the word null so obviously i am dong that wrong, and how would i go about creating a new list without that item? it wont let me use -= char1.item[counter].

Swapnil Sanghai
Ranch Hand

Joined: Dec 05, 2011
Posts: 41

For converting array to list you can use the asList(array) method

As you are getting null means that reference has nothing to refer. I think you got your solution for removing it.



Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10451
    
    8

brent carterHowever, when i set it to null it prints out the word null so obviously i am dong that wrong...[counter wrote:.

Check out the source code for String#valueOf(Object obj) for the solution to that mystery !
In case you didn't know, search for a file called src.zip under your JDK_HOME. That contains the source code for the Java library classes.

brent carter ........... and how would i go about creating a new list without that item? it wont let me use -= char1.item[counter wrote:.

Create the list from the array and then remove the List elements as and when required.
brent carter
Ranch Hand

Joined: Dec 15, 2011
Posts: 34
thanks guys...heres my progress and everything seems to work
 
jQuery in Action, 2nd edition
 
subject: adding and removing items from an array