dcsimg
ArrayList Restriction
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Shikhar_Rastogi
Posted On:   Sunday, September 4, 2005 08:28 AM


Can i restrict ArrayList someway for adding only Integer elements?

Re: ArrayList Restriction

Posted By:   srini_vasan  
Posted On:   Monday, September 19, 2005 09:31 AM

Upto java1.4 , it is not possible to restrict
the ArrayList to add only integers.


But we can make ArrayList to add Integers only ,

by using some wrapper class as follows




  import java.util.ArrayList;

public class IntegerArrayList extends ArrayList
{

public boolean add(Object o)
{
if(o instanceof Integer)
{
return super.add(o);
}
else
{
return false;
}

}

// similarly u should override other methods of ArrayList

}

Re: ArrayList Restriction

Posted By:   Jagadeesh_Kumar  
Posted On:   Monday, September 5, 2005 03:00 AM

Hi Shikar,
You cant restrict array list to add a specific primitive type like int, float etc. But u can just manually check the object type using IF condition before adding the type to arraylist.


Regards,
Jagadeesh

Re: ArrayList Restriction

Posted By:   WarnerJan_Veldhuis  
Posted On:   Sunday, September 4, 2005 01:04 PM

If you use Java5, yes: List myList = new ArrayList(); It's called "Generics"

If you use Java1.4 or less, no, unless you create a subclass of ArrayList, and override the add()-related methods like this:

public void add(Integer a) {
super.add(a);
}
About | Sitemap | Contact