Reputation: 35
I'm a java beginner and I know that you should use list over arraylist but i'm not exactly sure how to change from arraylist to list. Before I had
ArrayList<Homework3> hw = new ArrayList<Homework3>();
Which worked and then I tried:
List<Homework3> hw = new ArrayList<Homework3>();
Then I tried to implement the List interface with this:
public interface List<Homework3> // inheritance not shown
{
boolean add( Homework3 x );
void add( int index, Homework3 x );
Homework3 get( int index );
Homework3 remove( int index );
Homework3 set( int index, Homework3 x );
int size();
}
But now it's saying incompatible types. I looked at other questions and discussions and they had the code just like this:
List<Object> list = new ArrayList<Object>();
And i'm following the same basic principle, can someone help explain why it isn't working and how I can fix this?
Upvotes: 1
Views: 169
Reputation: 106389
You don't need to do any of this. Java takes care of this type resolution for you through generics.
Because List<E>
is defined in a generic way, so too must its implementors be, and thus ArrayList<E>
uses the same generic type declared by the interface.
To be explicit:
When you declare List<Homework3> hw = new ArrayList<Homework3>();
, everywhere that E
is used in the Javadoc is replaced by Homework3
. You don't have to implement any of this because the language already has for you.
Upvotes: 1
Reputation: 31858
The class java.util.ArrayList
implements java.util.List
interface. Hence your code after defining your own List<Homework3>
interface would have incompatible types.
List<Object> list = new ArrayList<Object>();
// ^^ ^^
// your.package.List java.util.ArrayList
Similar code in your question
List<Homework3> hw = new ArrayList<Homework3>();
// ^^ ^^
// java.util.List java.util.ArrayList
would have worked earlier since then you didn't introduce the List
interface as mentioned in the question and you were referring to java.util.List
itself.
Upvotes: 0