Type Safe Collections

Hello All,
I want to have type safe collections. Today. when we do programming with collections it almost behaves like a scripting language with no data types. any thing which is an object goes in and comes out freely.
what about having a Collection(vector, ArrayList) class which can contain objects of only one type.
something like
ArrayList<Integer> a = new ArrayList();
regards,
Abhishek.

Here's my way of using generics in normal Java - not quite as good as a compile error - but it works, and gives you a runtime error on inserting an object of the wrong type.
I did this when at Uni, hence all the funky comments (well, you can't expect the lecturers to actually read the code, can you?).
Just something you may find useful:
import java.util.*;
���An implementation of the Proxy pattern, designed to wrap any list, and make it accept
���objects of the specified type (subclasses are allowed) only, hence allowing a user of
���this class to 'trust' the Proxy list.
public class TypeSafeList extends AbstractList implements Serializable
���protected List source;
���protected Class acceptable;
���/**
������@param list the list to assign.
������@exception java.lang.IllegalArgumentException if the list contains elements of a
������different type to that specified
���*/
���public TypeSafeList(List list,Class acceptable)
���{
������Iterator iterator = list.iterator();
������while( iterator.hasNext() )
���������if( !acceptable.isInstance( iterator.next() ) )
������������throw new IllegalArgumentException( list+" contains elements not of type "+acceptable);
������this.source=list;
������this.acceptable=acceptable;
���}
���/**
������Passes on the request to the underlying list. See java.util.List.
���*/
���public Object get(int index)
���{
������return source.get(index);
���}
���/**
������Passes on the request to the underlying list. See java.util.List.
���*/
���public int size()
���{
������return source.size();
���}
���/**
������Checks that the type of the parameter is valid, and then passes on the
������request to the underlying list. See java.util.List.
������
������@exception java.lang.IllegalArgumentException if the type of the parameter is
������invalid.
���*/
���public Object set(int index,Object element)
���{
������return source.set(index,checkType(element));
���}
���/**
������Passes on the request to the underlying list. See java.util.List.
���*/
���public Object remove(int index)
���{
������return source.remove(index);
���}
���/**
������Checks that the type of the parameter is valid, and then passes on the
������request to the underlying list. See java.util.List.
���*/���
���public void add(int index,Object object)
���{
������source.add(index,checkType(object));
���}
���/**
������Return the Class object this List is configured to accept.
���*/
���public Class getAcceptable()
���{
������return acceptable;
���}
���
���/**���
������Checks the validity of the parameter against the protected field 'acceptable'.
������@return object if object is valid.
������@exception java.lang.IllegalArgumentException if the argument is invalid.
���*/
���protected Object checkType(Object object) throws IllegalArgumentException
���{
������if (acceptable.isInstance(object))
���������return object;
������throw new IllegalArgumentException(object+" needs to be of type "+acceptable.getName());
���}
}

Similar Messages

  • Generics simply aren't type-safe?

    From http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf page 15:
    In particular, the language is designed to guarantee that if your entire application has been compiled without unchecked warnings using javac -source 1.5, it is type safe.
    However, I can create this:
    import java.util.*;
    public class TypeUnsafe
         static public <T extends Collection> void workaround(T a, T b)
              a.addAll(b);
         static public void main(String[] args)
              Collection<Integer> a = new ArrayList<Integer>();
              Collection<String> b = new ArrayList<String>();
              b.add("Bwahahaha");
              workaround(a, b);
              System.out.println(a.iterator().next().intValue()); // ClassCastException
    }There are no casts or particular trickery involved, and this compiles without warnings using javac -source 1.5. Yet I just added a String to a Collection<Integer>. Despite T being defined as extending a raw type, the usual unchecked warning when calling a method with parameterised arguments on a raw type is not given.
    On the positive side, it gives me a handy alternative to the NYI @SuppressWarnings :)
    I've searched bug parade and the forums, but haven't come across this particular problem... I've only recently started playing with generics, so perhaps I'm missing some subtlety that explains why people aren't jumping up and down and screaming about this.
    Sorry if this has been discussed before, and I'm not yet familiar enough with the terminology to have found it in my searches.

    Few thoughts:
    - The program kingguppy has presented is an example of program with false sense of security despite using generics - the generic program compiles even without a warning but in the end it throws ClassCastException. I hope that we won't find many generic programs with such characteric. I'd say that the program does not benefit of generics because there is no contract between container and containee as far as parameters of workaround() method are concerned. Actually, as Michael said, it uses raw type (Collection). If possible we should avoid using raw types in generic programs. By the way, do you know that raw types might be deprecated in the future?
    - Micheal also sugested that in case when there is a conversion from parameterized type to raw type the compiler should emit a warning. I agree with him. I hope that kingguppy will file a bug report and let us know what "generic gurus" think about it. Funny, if the workaround() method were designed as
    static public void notGenerifiedMethod(Collection a, Collection b) {
      a.addAll(b);
    }the compiler would actually emit an unchecked warning. Perhaps, it's sometimes better not to use generified methods.
    - The reason why I presented let's say a possible or different solution to the original problem is because in the end it matters only if we, developers, can produce a workable solution. The bosses don't like to hear that there are bugs... I hope you all know what I mean. Who knows, there might be a reader of this forum who will find it useful.
    Your thoughts are welcomed.
    Andrej

  • I have type-safe generic array copying!

    Check this out. I get no warnings from this, and so far it seems to work fine, and it only takes twice the time of a normal array copy.
    All you have to do is pass in a dummy array of the same type as your inputArray, which under normal circumstances is very doable. The dummy array does not need to have the same dimension as the input array, which lets you use this as a static method in a utility class without feeling the burning need to make it throw an exception.
    It takes advantage of Collections' type-safe toArray() method.
         public static <T> T[] copyArray(T[] inputArray, T[] targetArray)
              return arrayToList(inputArray).toArray(targetArray);
         private static <T> ArrayList<T> arrayToList(T[] inputArray)
              ArrayList<T> returnValue = new ArrayList<T>();
              for(int i = 0; i < inputArray.length; i++)
                   returnValue.add(inputArray);
              return returnValue;

    And I like my tabs, thank you.Many people consider using tabs in code to be
    amatuerish. I can't say I disagree. Tabs are
    represented as different lengths depending on the
    editor. If you are using Eclipse, you can set it to
    insert a number of space when you hit tab instead of
    inserting tabs.I like tabs because they are an abstraction of indentation levels, something you don't get with spaces (unless you use one space per level), and therefore it makes more sense to me to use them. I use editors with good tab sizes that are also adjustable. Plus, I just like them better. So there.

  • How to exclude stock of a particular storage type from collective availabil

    How to exclude stock of a particular storage type from collective availability check in MDVP.

    you can set the storage location as 'Storage location stock excluded from MRP' value '1' in the field
    Sloc MRP indicator , in MRP view $ when you enter a storage location accessing the material master.
    Thsi is the only way to exclude the storage location, you have to do it per each material and also it is excluded from the MRP.
    With this option the stock is not considered in ATP.
    IF you need the storage location in the MRP, then you should consider the use of MRP Areas.
    With the MRP Areas you define which plants/storage locations belong to each MRP area and the ATP is performed for eah area with the stocks that exist in each of them.
    Please if the issue is solved set the thread  as answered and provide the points to the useful replies.
    thanks for your cooperation

  • Type safe bean interfaces (Java 5) and JBoss IDE

    I've posted this help request already in the appropriate JBoss forum.
    But unfortunately still without any response.
    Latest JBoss IDE versions support type safe business methods e.g. like
         * only for testing
         * @ejb.interface-method view-type = "both"
         * @ejb.permission role-name = "Default"
        public ArrayList<String> getSomeStrings()
        }But the interface methods will be always generated unsafe like
        * only for testing
       public java.util.ArrayList getSomeStrings(  )
          throws java.rmi.RemoteException;Is this a known problem or is something wrong with my xdoclet configuration?
    Thanks in advance
    Torsten

    Yep... I think that's what I found. By using public methods in my enum class to map it's string member to the EJB field I was able to effectively use my enum in the EJB. The container does it work with a String but the EJB's clients only deal with a enum field. That's what I originally intended so, thanks for your response.

  • 1067: Implicit coercion of a value of type void to an unrelated type mx.collections:ArrayCollection.

    Here is what I have going on.
    When a button in my app is clicked it will instantiate a new object called ButtonCommand, within that object I create a new instance of a ListVO called vo.  I then reference my model object that also has a separate instance of the same Value Object ListVO class, reference its properties and place it into the corresponding property of the new VO object. Here is the code.
    var vo:ListVO = new ListVO();
    vo.name = model.list.name;
    vo.id = model.list.id;
    vo.amount = model.list.amount;
    vo.category = model.list.category;
    Within that same ButtonCommand class, next line I am trying to add the new ListVO instance to an arrayCollection that is also referenced from my model object, so here is the code for that.
    model.listCollection = model.listCollection.addItem(vo);
    I get the following error : -1067: Implicit coercion of a value of type void to an unrelated type mx.collections:ArrayCollection.
    And here is my getter/setter for the model.listCollection.
    public function get listCollection ():ArrayCollection
          return _listCollection;
    public function set listCollection(value:ArrayCollection):void
          _listCollection = value;
    Any Ideas?

    I thought model.listCollection is an ArrayCollection?
    model.listCollection is an ArrayCollection as shown in the example model code a few posts back.
    public class Model extends Actor
         //- PROPERTIES - //
         //-- other properties are here
         private var _listCollection:ArrayCollection = new ArrayCollection();
         public function Model()
         super();
         //other getter and setters here
         public function get listCollection ():ArrayCollection
         return _listCollection;
         public function set listCollection(value:ArrayCollection):void
         _listCollection = value;
    I am finding this to be very odd, seems like a simple getter setter situation, but I feel I must be missing something. The code trace(model.listCollection); should trace out as an ArrayCollection and not the VO object I am trying to add to it. Also when i run the code model.listCollection.addItem(vo); it should add the vo to the array collection through my setter, but yet it seems to try to access my getter.
    I took Kglads advice and traced out  _listCollection within my getter before my return statement and it returns [object ListVO]..... confused for sure. I am going to change the _listCollection property in the model from private with a getter/setter to a public and see what happens.

  • What does it mean by "Deprecation of MBeanHome and Type-Safe Interfaces" ?

    The "Javadoc" for the type safe WebLogic MBean interfaces have this disclaimer;
    Deprecation of MBeanHome and Type-Safe Interfaces... This is a type-safe interface for a WebLogic Server MBean, which you can import into your client classes and access through weblogic.management.MBeanHome. As of 9.0, the MBeanHome interface and all type-safe interfaces for WebLogic Server MBeans are deprecated. Instead, client classes that interact with WebLogic Server MBeans should use standard JMX design patterns in which clients use the javax.management.MBeanServerConnection interface to discover MBeans, attributes, and attribute types at runtime.
    Link: http://otndnld.oracle.co.jp/document/products/wls/docs100/javadocs_mhome/weblogic/management/configuration/DomainMBean.html
    I don't understand what this means;
    1) Is all the WebLogic MBean interfaces in the "weblogic.management.configuration.*" deprecated?
    2) Is the usage of MBeanTypeService also deprecated. since it requires the an WebLogic MBean interface as input for it's getMBeanInfo method?
    3) If the WebLogic MBean interfaces will dispear, wil there be any reliable source for type information about WebLogic MBean since the information returned by MBeanTypeService.getMbeanInfo(), MBeanserver.getMbeanInfo() or WebLogicObjectName.getMbeanInfo() isn't consist in its naming schemes (tries to but..)?

    Hi,
    While scheduling background job, you can trigger the job based on existing job status as dependency or schedule the job based on the SAP Event.
    Dependency Job like first background job completes successfully then second followup job will executed other job will not triggered.
    Event Jobs: While importing data through transportation, some RDD* jobs automatically triggers. These are event based jobs.
    Regards,
    Ganesh
    ****Reward points if Helpful*****

  • Which type of collection is suitable for below scenario?

    which type of collection is suitable for below scenario?
    A) session.getAttibute("userPref",dad_re);
    possible values inside session are rad_eu,tcd_nid,aa,iod_po
    B)Need to compare with below set of values .
    dad_re
    rad_eu
    aad_vv
    bbd_rt
    ccd_ff
    If matched
    sysout("Matched values"+rad_eu)
    else
      sysout("Non matching with B"+tcd_ni)
    A - will contain only one value for each time and it is superset
    Which collection will use to store B?

    A HashSet.

  • Which order type gets collected and is used for forecast consumption

    Hi all,
    I would like to know which Order Types (transaction types) get collected into ASCP (appear as demand) and which Order Types are used for forecast consumption.
    I tried to find something in the user guides, but had not yet success :(
    What I want to do:
    1. decide which order types are collected or not
    2. decide which order types consume forecast or not
    Anyone any advices?
    Big thanks in advance,
    David.

    Hi,
    Rather speaking like Order types, we may use word Sales Order. ASCP will collect all the Sales Orders for which we need to intiate action for Supplies. How it is determined?. It is determined from SO lines where in we have So lines are scheduled(it is prt of Workflow action too) and It is flaged 'Yes' for "Visible Demand Flag" . This is what designed functionality. We do not care what type of order type it is.
    thanks,
    dr

  • Memory cost of each type of Collection class

    Hi, I wonder what is the memory cost of each type of Collection?
    Suppose I want to keep a set of non-duplicate objects, HashSet removes duplicates automatically, but calculating hash is extra cost; instead i can use ArrayList and do a check "if contains, then adds" before adding an element. Which one is faster? And which costs less memory?
    Thanks alot!

    Use a Set, that's what it is there for.

  • Axis - Using type safe enumerations as parameters.

    I defined the following:
    interface A {
    foo(E x);
    where class E is a type safe enumeration (NOT a Java1.5 enum).
    When using java2wsdl | wsdl2java i get:
    interface A' {
    foo(String x);
    And then all the stubs and skeletons are implementing A' so I can't use my A. How can I stop axis from doing this?

    Hi,
    AFAIK, you can't. I'm not an expert though, so everything below may not be the best solution.
    The best way I have found for dealing with enums is to declare them as such in your schema, viz:
          <simpleType name="HoldStatus">
            <annotation>
              <documentation>The status of a hold.</documentation>
            </annotation>
            <restriction base="string">
              <enumeration value="INACTIVE"/>
              <enumeration value="ACTIVE"/>
            </restriction>
          </simpleType>Then, most WSDL->Java tools will do something sensible with this, making their own form of enum. I don't know about Axis, but Weblogic's wsdl2service does this.
    Then you still have to map between the generated enum and your one. This is the best solution I'm aware of, though.
    As far as running java2wsdl then wsdl2java - I'm not aware of any tools that will do 'round tripping' like this successfully. I'd be keen to hear of some if there are any though :-D
    -Tim

  • Type-safe enum in CMP EJB field...

    Is it possible to use a type-safe enum like this in an EJB CMP field?
    I have tried to do that but although the code compiles I get errors.
    package dataBeansPkg;
    import java.io.Serializable;
    import java.io.ObjectStreamException;
    import java.util.HashMap;
    public final class Estado implements Serializable
    private static final String ACTIVODESC = "Activo";
    private static final String INACTIVODESC = "Inactivo";
    private static final String ELIMINADODESC = "Eliminado";
    private static final String BLOQUEADODESC = "Bloqueado";
    private static HashMap VALUES = new HashMap();
    private final String status;
    private final String descripcion;
    public static final Estado ACTIVO = new Estado("A", ACTIVODESC);
    public static final Estado INACTIVO = new Estado("I", INACTIVODESC);
    public static final Estado ELIMINADO = new Estado("E", ELIMINADODESC);
    public static final Estado BLOQUEADO = new Estado("B", BLOQUEADODESC);
    protected Estado()
    this.status = null;
    this.descripcion = null;
    protected Estado(String estado, String descripcion)
    this.status = estado;
    this.descripcion = descripcion;
    VALUES.put(estado, this);
    public String getValor() { return status; }
    public String getEstado() { return status; }
    public String getDescripcion() { return descripcion; }
    public String toString() { return getValor(); }
    public final boolean equals(Object o) { return super.equals(o); }
    public final int hashCode() { return super.hashCode(); }
    public static Estado find(String estado)
    if(VALUES.containsKey(estado)) {
    return (Estado)VALUES.get(estado);
    return null;
    public Object readResolve()
    Object result = find(status);
    if(result != null)
    return result;
    else
    return INACTIVO; // valor por omision
    Whenever I run a client using the bean with a field associated to this enum, I get...
    java.io.StreamCorruptedException: Caught EOFException while reading the stream header
    and
    Error loading state: java.io.StreamCorruptedException: Caught EOFException while reading the stream header
    Is it possible to use a type-safe enum as a field in an CMP bean?

    Yep... I think that's what I found. By using public methods in my enum class to map it's string member to the EJB field I was able to effectively use my enum in the EJB. The container does it work with a String but the EJB's clients only deal with a enum field. That's what I originally intended so, thanks for your response.

  • Bad index type for collection access ???

    Hi there,
    I am writing a script in VBA to connect to SAP.
    I encountered something strange.
    Why does this work:
    Set oSession = oConnection.Children(0)
    But this isn't:
    X = 0
    Set oSession = oConnection.Children(X)
    It results in an error: "Bad index type for collection access"
    Regards, Bas Prins

    Thanks,
    Although that is not proper VBA syntax I understand your suggestion.
    In VBA that would be:
    DIM X AS INTEGER
    X = 0
    Set oSession = oConnection.Children(X)
    But I tried several datatypes, all resulted in error.
    Regards, Bas.

  • What's "type-safe" ?

    when something is type-safe, what does that mean?

    http://en.wikipedia.org/wiki/Type_safe
    It's amazing what the wide world of web contains.

  • Runtime type of Collection contents?

    I'm pretty certain I know the answer to this question, but anyway:
    In a JavaBean editor, one property of the bean may be a collection of (potentially editable) beans. To edit the property I can display the appropriate editor if I can determine the type of the bean in the collection. A dirty but effective solution is to sample the collection and see what's actually in it. But in the case of an empty collection that isn't possible. (One function of the editor is to add a new bean to the collection.)
    It seems that my only alternative is myCollection.getClass().getTypeParameters(), which tells you what the parameters were when the type was declared, e.g. for Vector<E>, "E", which obviously isn't any help, although it is consonant with the rule that the type parameter "disappears at runtime". (In other words, that Java is a statically typed language.)
    I just want to confirm that I'm not missing something.
    (Btw, a potential, though labor-intensive, solution is to set the collection element type in a BeanInfo attribute. So it's not like this is a dead end. I just want to confirm that I'm understanding it correctly.)
    TIA

    AH HA! It works, but don't ask me why (yet). Here's some test code, using a Method rather than a Field since accessor methods are available through Introspection while Fields aren't:
    public class ATestBean {
        public static void main ( final String[] args ) throws Throwable
            ATestBean bean = new ATestBean();
        public ATestBean ( ) throws Throwable {  super();
            Method m = getClass().getDeclaredMethod("getCollection", new Class[0] );
            Class<?> c = getClassType( m );
        public Collection<AConcreteClass> getCollection()  {
            return null;
        public Class<?> getClassType(final Method meth ) throws Throwable {
            Type type = meth.getGenericReturnType();
            String strType = null;
            if (type instanceof ParameterizedType) {
                String actual = Arrays.toString( ((ParameterizedType)type).getActualTypeArguments() );
                   // actual <- "[class com.x.y.z.AConcreteClass]"
                strType = actual.substring( 7, actual.length()-1 );
            if (strType != null) {
                Class<?> klass = Class.forName(strType);
                return klass;
            return null;
    }Learn something new every day. Thanks.
    Hmmm, looks like Introspector is due for an update...

Maybe you are looking for