Casting between ArrayLists in Java

后端 未结 6 641
故里飘歌
故里飘歌 2020-12-15 11:56

Sorry, I thought this was an inheritance question: it was an ArrayList question all along!

Ok, my problem is more specific than I thought. So I have two families of

6条回答
  •  清歌不尽
    2020-12-15 12:41

    As stated, you cannot cast ArrayList to ArrayList, but you can cast ArrayList to ArrayList. Or better use List as your return value, because you probably don't rely on the ArrayList implementation anyway:

    protected ArrayList getCardBox();
    

    As for your question in the comment, the construction should work as you described: List list = new ArrayList();. You probably have to fill your list, so the method is probably something like this:

    protected ArrayList getCardBox() {
        List list = new ArrayList();
        list.add(pokerCard1);
        list.add(pokerCard2);
        return java.util.Collections.unmodifiableList(list);
    }
    

提交回复
热议问题