编译结果如下:
FillDemo.java:22: error: incompatible types: no instance(s) of type variable(s)
T exist so that List<? super T> conforms to ArrayList<String>
al=fillSome(al,"a",2,4);
^
where T is a type-variable:
T extends Object declared in method <T>fillSome(List<? super T>,T,int,int)
1 error
- /*
- 需求:将List的部分元素替换
- */
- import java.util.List;
- import java.util.ArrayList;
- import java.util.Collections;
- class FillDemo
- {
- public static void main(String[] args)
- {
- ArrayList<String> al = new ArrayList<String>();
- al.add("asdf");
- al.add("asd");
- al.add("dd");
- al.add("asdfghoj");
- al.add("z");
- al.add("no");
- System.out.println(al);
- al=fillSome(al,"a",2,4);
- System.out.println(al);
- }
- public static<T> List<? super T> fillSome(List<? super T> list,T obj,int fromIndex,int endIndex)//包含头不包含尾
- {
- if(fromIndex>endIndex)
- throw new ArrayIndexOutOfBoundsException("Array index out of bounds:"+(fromIndex-endIndex));
- if(fromIndex>list.size())
- throw new ArrayIndexOutOfBoundsException("Array index out of bounds:"+fromIndex);
- if(endIndex>list.size())
- throw new ArrayIndexOutOfBoundsException("Array index out of bounds:"+endIndex);
- for(int i=fromIndex;i<endIndex;i++)
- list.set(i,obj);
- return list;
- }
- }
复制代码
|