Logan
Logan

Reputation: 2505

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 Object, 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?

Upvotes: 1

Views: 1113

Answers (4)

java_mouse
java_mouse

Reputation: 2109

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.

Upvotes: 0

Nrj
Nrj

Reputation: 6831

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)

Upvotes: 0

Thilo
Thilo

Reputation: 262534

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

Upvotes: 2

Cameron Skinner
Cameron Skinner

Reputation: 54326

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.

Upvotes: 3

Related Questions