开发者

Allowing Only Specific Class Objects in ArrayList

I Know I can use Generics while defining the ArrayList to do that. But here the case is different.

I have a ArrayList, which when defined accepts any type of Objects. Once the user inserts the first O开发者_StackOverflowbject, I need to use Class Reference to Find the Class of that Object and then have to ensure that only Objects of that Class are inserted in the ArrayList.

Example:

ArrayList arrayList = new ArrayList();

Now lets say the User enters an object b, of Class B in the arrayList, then from now onwards, I must only allow objects of type B to be added to the arrayList.

I know that I can find the class of the Object inserted using:

arrayList.get(0).getClass();

But what after it? How will I use the Class type I just found?


Since this is an interview question I won't give you a complete answer, but you might want to take a look at the Class.isAssignableFrom method.


You cannot use generics for this, you need to implement runtime checks.

One way would be to subclass ArrayList and implement the various add methods in a way that checks the type of what is being added.

get(0).getClass().cast(newObject);
// will throw a ClassCastException if it does not match


hmm .. you can do the comparison on the class names - not elegant but should do your work ..

get(0).getClass().getName().equals(classname for the pushed value)


I see some design issues in the code rather how to solve this issue. The flow of the code should determine what the code is doing so that it does not send the collection to a method which can put any arbitrary objects (by checking or not) in it.

I would advise to revisit the design.

For example, if someone is trying to put a soccer ball into the collection and then the collection should be passed into a method where it can deal with a soccer ball. They can use a common code or command pattern for handling any ball or specific behavior for soccer ball and so on.

The same is true if the code wants to put a base ball into a collection, it better knows what its going to do next.

It is a design issue... It is not a code issue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜