简体   繁体   中英

How can I restrict the arraylist to accept only a specfic type of object prior to generic

我们如何才能限制arraylist在泛型之前只接受特定类型的对象

Write a wrapper function that accepts only the allowed type, and hide the collection. That was standard best-practice pre-Java-5.

private final List strings = new ArrayList();

public void add(String s)
{
    strings.add(s);
}

public String remove(String s)
{
    return (String) strings.remove(s);
}

// etc...

Yes, this sucks.

Might I ask: is there a reason you're not using generics? They are bytecode-compatible with Java 1.4

Two options, (I am assuming C# here, but all applies to pretty much all OO languages).

1) Inherit from collection type of choice (or its interfaces), override all methods to throw exception on wrong type, something like this:


public class MyType
{
    // Your type here
}

public class MyTypeCollection : ArrayList
{
    public override int Add(object value)
    {
        if (!(value is MyType))
        {
            throw new ArgumentException("value must be of type MyType");
        }

        return base.Add(value);
    }

    public int Add(MyType myType)
    {
        return base.Add(myType);
    }

    // Other overrides here
}

or 2) (probably better), create your own type altogether and implement interfaces as desirable for collections and use a non-generic, non-typed collection internally. Something like this:



public class MyTypeCollection2 : IEnumerable
{
    private readonly ArrayList _myList = new ArrayList();

    public void Add(MyType myType)
    {
        _myList.Add(myType);
    }

    // Other collection methods

    public IEnumerator GetEnumerator()
    {
        yield return _myList.Cast<MyType>();
    }
}

Make sure to implement all interfaces you will care about. In the .NET Framework the interfaces implemented for ArrayList are: IList, ICloneable

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM