Problem overriding ArrayList add method

前端 未结 7 1757
一整个雨季
一整个雨季 2021-01-27 19:45

I have a class that is extending Java\'s ArrayList. I\'m currently using Java build 1.6.0_22-b04. Looks like this:

public class TokenSequence extends ArrayList&         


        
7条回答
  •  清歌不尽
    2021-01-27 20:36

    First of all, in the current implementation it will go to infinite recursion when you will try to call add function with instance of TokenSequence. Did you mean to call "addAll" in that case?

    Second, forget about

    void add(Object)
    

    in you case you need to add 2 methods (make them return boolean, if you want to be consistent):

    public void add(String o) {
      add(new Token(o.toString()));
    }
    
    public void add(TokenSequence t){
      addAll(t);
    }
    

    and the add(Token) is already implemented by ArrayList

    on the other hand, if you want a single method, you can declare, for example:

    public void add(Serializable t)
    

    this method will be called for both TokenSequence and String. unfortunately to make the same method executed for Token (as oppose to the one provided by ArrayList), you will need:

    1. make sure Token implements Serializable
    2. cast Token to serializable

    i.e:

    add((Serializable)new Token())
    

提交回复
热议问题