0

I want to implement a function with signature

static boolean checkAnyOutOfBoundary(int[] index,ArrayList<ArrayList<T>> list)

Where I want to substitute T with other self-created class(DocScore). I tried to substitute T with Object. But when I try to instantiate the list instance, like

ArrayList<ArrayList<Object>> DocScoreList = new ArrayList<ArrayList<Object>>();
for (int i = 0; i < index.length; i++)
DocScoreList.add(root.children.get(i).docList);

The type of root.children.get(i).docList is ArrayList<DocScore>

I can not add element into DocScoreList. Does anybody know how can I implement this?

4
  • 1
    what's the error message? Also, what type is root.children.get(i).docList, is an ArrayList<Object>? Commented Feb 15, 2013 at 19:39
  • 3
    static boolean <T> check... Commented Feb 15, 2013 at 19:39
  • @JanDvorak it could be public class SomeClass<T>... Commented Feb 15, 2013 at 19:40
  • It wouldn't matter, since the function is static. Commented Feb 15, 2013 at 19:47

3 Answers 3

1

So you are adding an ArrayList<DocScore> to a ArrayList<ArrayList<Object>> but the add method expects an ArrayList<Object>.

Can you provide an ArrayList<DocStore> where ArrayList<Object> is required? No, because A bag of banana is not a bag of fruit

So DocScoreList has to be an ArrayList of something to which a ArrayList<DocStore> can be added. Some examples are:

  • ArrayList<DocStore> actual type
  • List<DocStore> because ArrayList<T> is a List<T>
  • ArrayList<? extends Object> a list of some unknown type that (directly or indirectly) extends Object. Since DocStore meets the criteria ? extends Object this will work.
  • List<? extends Object>
  • etc. You get the idea.
Sign up to request clarification or add additional context in comments.

Comments

0
static <T> boolean checkAnyOutOfBoundary(int[] index,ArrayList<ArrayList<T>> list)

Example of calling it:

boolean b = checkAnyOutOfBoundary( new int[]{0,1}, new ArrayList<ArrayList<String>>());

1 Comment

How can I invoke this function with specific T? Btw, eclipse shows above is not the right way to write an function...
0

Because even in the case that Bar is a subclass of Foo, an ArryList is not a superclass of ArrayList.

Change

ArrayList<ArrayList<Object>> DocScoreList = new ArrayList<ArrayList<Object>>();

to

ArrayList<ArrayList<? extends Object>> DocScoreList = new ArrayList<ArrayList<? extends Object>>();

1 Comment

Do you mean I should write ArrayList<ArrayList<DocScore extends Object>> directly in the DocScoreList declaration or extends Object class in the DocScore class definition?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.