Hey guys,
I'm trying to figure out best practices for some lists that I am working with and was hoping someone could set the record straight. It would seem that the best way for me to do what I want to do is to extend ArrayList, but I have read around that it's not the best practice. Basically, I'm working with some lists and want to pull out certain data from them, or set some of the data that's not set, or change some of the data depending on what it says. A good example is the one below, where say I have a list of cats and want to find out which one is the biggest. Excuse the extreme amount of code, but I want to get my point across. Here are three different ways to do this, first being extending ArrayList, next being making a new class with an internal ArrayList, and the last is just having a method in the main class or some other class to complete the task. I've also shown how you'd use them:
public class CatList1 extends ArrayList<Cat>
{
public int maxSize()
{
int max = 0;
for(Cat c: this)
{
if(c.getSize() > max)
max = c.getSize();
}
return max;
}
}
public class CatList {
ArrayList<Cat> myCats = new ArrayList<Cat>();
public int maxSize()
{
int max = 0;
for(Cat c: myCats)
{
if(c.getSize() > max)
max = c.getSize();
}
return max;
}
}
public class NewClass
{
public static void main(String[] args)
{
NewClass go = new NewClass();
//extend ArrayList
CatList1 someCats = new CatList1();
Cat fluffy = new Cat();
someCats.add(fluffy);
int largest = someCats.maxSize();
//new CatList object with internal ArrayList
CatList moreCats = new CatList();
Cat socks = new Cat();
moreCats.myCats.add(socks);
largest = moreCats.maxSize();
//method in our main class
ArrayList<Cat> lotsOfCats = new ArrayList<Cat>();
Cat jack = new Cat();
lotsOfCats.add(jack);
largest = go.maxSize(lotsOfCats);
}
public int maxSize(ArrayList<Cat> cats)
{
int max = 0;
for(Cat c: cats)
{
if(c.getSize() > max)
max = c.getSize();
}
return max;
}
}
There might be some syntax and other errors in there (i.e. using main to do stuff) and I know I probably didn't encapsulate everything (myCats comes to mind), but you get the idea. So is any of these the best way to do this? Extending ArrayList seems to make things the easiest. The second technique adds an extra level of referencing when you start working with the list itself. The third just seems messy since you're not tying the method to any relevant object. Is there a better way to do this? I read something somewhere about using delegation methods, but not sure what that is and if it's supported in netbeans.