sartysam
sartysam

Reputation: 93

How to restrict elements of an ArrayList without using generics

Suppose I have an Employee class. How can I implement an ArrayList only containing Employee elements without using generics? That is, without Arraylist<Employee>, how can I restrict the ArrayList to add only Employee objects?

Upvotes: 2

Views: 1227

Answers (6)

newacct
newacct

Reputation: 122449

What exactly do you want when you "restrict"? There are two possible places where one could place a restriction: at compile-time or runtime.

Generics is a purely compile-time thing. It helps you write correct code but you can still bypass it and put the wrong type in the array and it won't complain at runtime.

On the other hand, something like Collections.checkedList()is a runtime restrictions. It throws an error at runtime when an object of the wrong type comes. But it does not help you at compile-time if you do not have generics.

So the two things are orthogonal, and neither is a replacement for the other. What exactly do you want?

Upvotes: 0

Don McCurdy
Don McCurdy

Reputation: 11970

If you're wanting to avoid generics for their own sake, e.g. for compatibility with very old versions of Java, then extending or wrapping ArrayList won't help - you probably want to find or make another array implementation that has the same functionality.

Basically, ArrayList is just a wrapper for a primitive array that copies and pastes its data into a larger array when necessary, so this isn't especially difficult to write from scratch.

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

Reputation: 346317

You could use Collections.checkedList() - but why would you want to not use generics?

Upvotes: 8

tskuzzy
tskuzzy

Reputation: 36476

Subclass the ArrayList class and name it something like EmployeeArrayList.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You could use a wrapper class that holds a private ArrayList field, say called employeeList, has a

public void add(Employee employee) {
   employeeList.add(employee);
}

as well as any other necessary methods that would allow outside classes to interact with the ArrayList in a controlled fashion.

I find it much better to use composition for this than inheritance. That way if you wanted to change from an ArrayList to something else, say a LinkedList, or even something completely different, you would have an easier time.

Upvotes: 8

Jigar Joshi
Jigar Joshi

Reputation: 240908

Extend ArrayList and customize add() and addAll() method to check the object being added is instanceof Employee

Upvotes: 8

Related Questions