Say I have these two ArrayLists:
ArrayList<Book> book = new ArrayList<>();
ArrayList<Journal> journal = new ArrayList<>();
Book
and Journal
are two different classes.
Both Book
and Journal
objects have a getYear()
method. I want to make a method that passes in an unknown ArrayList type and compares a passed in year to an object in the list. The following code is in main:
public static void fooBar(int year, ArrayList<?> list)
{
if(list.get(0).getYear() == year) // does not work!
{
}
}
If an unknown type is passed into the method, I cannot use that object's methods (getYear()
). How can I do this without making two methods that do the same thing (one for Book
and one for Journal
)?
In order to solve your problem, you need to create a new ArrayList by using the "new" keyword and then adding all of the objects, or use the clone() method.
So, first, make ArrayList as an instance variable to the PetList class so that it can be accessible through an object even outside the constructor. Then, you can provide an eatAll() method which iterates the ArrayList<Pet> and call the eat() method on all pet objects.
Yes, because You just pass a reference of ArrayList -Object, to your Object .
If I understand well that you want to access an ArrayList in another class? if in the case, you can use the getter and setter technique while declaring private ArrayList variables. Show activity on this post. ArrayList custName = new ArrayList(); ArrayList custZip = new ArrayList();
You can make an interface (if it doesn't already exist) (possibly named HasYear
) that declares the getYear()
method, and have Book
and Journal
implement it.
Then you can have your fooBar
method take an ArrayList
of some type parameter that is a HasYear
.
public static void fooBar(int year, ArrayList<? extends HasYear> list)
The ? extends
is due to the fact it's a consumer and not a producer.
Like JonK said, if they share a superclass or interface that defines getYear() then this will be made easier. Actually, the have to have either of those two relationships to make your proposed relationship.
interface HasYear {
public int getYear();
}
Book.java
public class Book implements HasYear{
//...
public int getYear(){/*YOUR IMPLEMENTATION*/}
}
Journal.java
public class Journal implements HasYear{
//...
public int getYear(){/*YOUR IMPLEMENTATION*/}
}
Now, you can create and use your ArrayList like this:
public static void fooBar(int year, ArrayList<? extends HasYear> list){
if(list.get(0).getYear() == year){
//yay
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With