Reputation: 191
Why is it not possible to do something like this?
RowList<List<Value>> extends ArrayList<List<Value>>
Also, how is it possible to do this?
RowList<Value> extends ArrayList<List<Value>>
I'm trying to implement a List
to be used in a database
, and want to extend ArrayList
so I'm able to check that the .add(),.set()
etc. methods do not violate the requirements of the Database
(not adding two rows with the same keys etc). I realise that it's probably not the best way to implement a database
, but it's an assignment for college that required us to do it this way.
EDIT: Using the 2nd option (that compiles), how is it possible to access the Values within the Lists that the RowList class holds?
Upvotes: 4
Views: 495
Reputation: 1390
The following two lines are identical (to the compiler), this is true even if you have a class called Value
as the named parameter will mask the class type
class RowList<Value> extends ArrayList<List<Value>>
class RowList<T> extends ArrayList<List<T>>
The reason for this is because value inside the first <>
is a named type parameter. So when you attempt to do something like
class RowList<List<Value>> extends ArrayList<List<Value>>
You have attempted to create a named type paramter List<Value>
which (in Java) is an invalid identifier, but instead you will get an error something like Syntax error on token(s), misplaced construct(s)
I think instead you are really trying to write
public class RowList extends ArrayList<Value> {
@Override
public boolean add(Value e) {
// TODO Custom code to check and what not
return super.add(e);
}
}
Where Value
is a custom object in your codebase. Then elsewhere in your code you can do:
RowList rl = new RowList();
rl.add(new Value(...));
Value v = rl.get(i);
EDIT:
The previous example assumes that the Value
class is an entry row of data. If instead it is a single item of data, and the row is represented by a List
then it would be more like the following:
public class RowList extends ArrayList<List<Value>> {
@Override
public boolean add(List<Value> e) {
// TODO Custom code to check and what not
return super.add(e);
}
}
RowList rl = new RowList();
List<Value> row = new ArrayList<Value>();
row.add(new Value(...));
rl.add(row);
List<Value> rowGet = rl.get(i);
Upvotes: 6