user1096311
user1096311

Reputation:

Is this approach fine for returning a copy of a list?

I have this question. I have two hierarchies, one of Animal and other of AnimalStore.

public abstract class Animal{
//Some members
}

public class Dog extends Animal{
//Some members
}

public abstract class AnimalStore{
//Some members
private List<Animal> animals;
public abstract void addAnimal(Animal a);
//Methods forwarding some List methods
//remove, find, count, 
}
public Animal get(int n){
return animals.get(n);
}
//Method for returning a copy of the list.


public class DogStore extends AnimalStore{
//some memebers
public void addAnimal(Animal a){
//Assert is a dog because this is a Dogs Store
}
}

I have some methods of List class using method forwarding in the AnimalStore. I have a method for getting the list where I create another List and iterate getting from animals and setting to newList. then I return newList as a copy of the new List. This is a pain in hte RAM zone because my GUI framework receive this list when creating a page (Im using Wicket BTW). Lets say 10, 000 users visit the page. So the method will be creating 10, 000 copy list. Worst!. If they just refresh the page will happen also. I dont want to return the original list because I dont want to client add cats to the DogStore list of animals.

Upvotes: 0

Views: 90

Answers (1)

thedayofcondor
thedayofcondor

Reputation: 3876

You can enforce stricter compile type checking with templates:

public abstract class AnimalStore<T extends Animal> {
    //Some members
    private List<T> animals;

    public abstract void addAnimal(T a);

    //Methods forwarding some List methods
    //remove, find, count, 

    public T get(final int n) {
        return animals.get(n);
    }
}

//Method for returning a copy of the list.

public class DogStore extends AnimalStore<Dog> {
    //some memebers
    @Override
    public void addAnimal(final Dog a) {
        //Assert is a dog because this is a Dogs Store
    }
}

public abstract class Animal {
    //Some members
}

public class Dog extends Animal {
    //Some members
}

Written this way, you remove the requirement to have to create a copy because I dont want to client add cats to the DogStore list of animals.

Upvotes: 2

Related Questions