开发者

I want to resolved a generic type E to a variable

I have to add this statement public void removeRange (int fromIndex, int toIndex) to my ListType class.

This method should remove all the elements with indexes in the range of fromIndex (inclusive) and toIndex (exclusive). All of the succeedng elements in the list should be shifted toward the front of the list to occupy the gap left by the removed elements. This method should trown an IndexOfBoundException if either of the specified indexes is invalid.

When I try to use a Generic type E to resolved a variable in this method, I get a error. Error Message "E cannot be resolved to a variable"

My code 

public void removeRange(int fromIndex, int toIndex)
   {
      if (fromIndex >= elements || fromIndex < 0 || toIndex >=elements || toIndex<0 ||   toIndex<=fromIndex)
      throw new IndexOutOfBoundsException();
      for( int i = 开发者_高级运维fromIndex; i <toIndex; ++i)
      E temp = remove(i);
   // Return the element that was removed.
      return;
   }

I know I can't declare a generic type E object, but I don't how to get around this?


Try

public E removeRange<E>(int fromIndex, int toIndex)
   {
      if (fromIndex >= elements || fromIndex < 0 || toIndex >=elements || toIndex<0 ||   toIndex<=fromIndex)
      throw new IndexOutOfBoundsException();
      for( int i = fromIndex; i <toIndex; ++i)
      E temp = remove(i);
   // Return the element that was removed.
      return temp;
   }


Your ListType class should declare that it takes generic type E. So you want something like:

public class ListType<E> extends ArrayList<E> {
    public void removeRange(int fromIndex, int toIndex) {
        // your remove logic here
        ...

        // now you can use E here
        E temp = remove(i);
        return;
    }
}

I'm guessing that you're extending ArrayList here. Either way it's the same concept.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜