Java – lists and lists
•
Java
Why lose type security when using list and use list < Object >? Aren't they basically the same?
Editor: I found the following compilation errors
public class TestClass { static void func(List<Object> o,Object s){ o.add(s); } public static void main(String[] args){ func(new ArrayList<String>(),new Integer(1)); } }
And this is not
public class TestClass { static void func(List o,new Integer(1)); } }
Why?
Solution
No, they're not the same thing
If you provide an API,
class API { static List<Object> getList() { ... } static void modifyList(List<Object> l) { ... } }
Improper use of client
List<Integer> list = API.getList(); API.modifyList(list); for (Integer i : list) { ... } // Invalid
So when your API specifies list < Object > they get a compile time error, but when the API GetList () returns a list and the API When modifylist (list) accepts a list without generic type parameters, they will not
Edit:
In the comments you mentioned change
void func(List<Object> s,Object c) { s.add(c); }
to
void func(List s,Object c) { s.add(c); }
so that
func(new List<String>(),"");
I can work
That's illegal security The type safe way to do this is
<T> void func(List<? super T> s,T c) { s.add(c); }
This basically means that func is a parameterized function, which accepts a list, whose type can be any superclass of T, and the value of type T, and adds the value to the list
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码