• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

adding and removing items from an array

 
brent carter
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
Java Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11096
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
brent carter
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
Java Oracle Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11096
13
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks guys...heres my progress and everything seems to work
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic