• Post Reply Bookmark Topic Watch Topic
  • New Topic

About ArrayList  RSS feed

 
vara prasad
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my requirement is how can i put only String objects in ArrayList.
whenever i put some othertype(primitive or any other objects) it has shown an error.
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To enforce a "String Only" policy, wrap the array list in you own object and write set(String) and get() methods that do the necessary casting for you.

Primitives can not go in an array list. You have to wrap them with their object counterparts (IE: Integer)
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66306
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vara, please be sure to post your topics in the appropriate forum.

This forum is for questions related to JSP technology. Since your question is not, I'm moving it to the Java in General (intermediate) forum.

thanks,
bear
Forum Bartender
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stretching the intermediate bounds a bit ... In JDK 5 you can also use "generics" to specify what is in a collection. If you write something like this:

List<String> myList = new ArrayList<String>();

You will only be able to put strings in and you can get them back out without casting.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!