Die*_*ego 21 java generics list
为了保存一个由一个成员完成支付的ArrayList,我想将支付ID列表更改为一个字符串,所以我创建了以下方法:
public String fromArraytoString(ArrayList items){
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
return json.toString();
}
Run Code Online (Sandbox Code Playgroud)
但我收到以下警告:
ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized
Run Code Online (Sandbox Code Playgroud)
谁能解释我为什么?
Nat*_*tix 48
你肯定应该阅读关于Java泛型的这个教程:http: //docs.oracle.com/javase/tutorial/java/generics/
简而言之:
许多Java类和类型(称为泛型类或泛型类型),通常是集合,都有所谓的类型参数,例如Ein ArrayList<E>(E只是一个任意选择的名称,其他类将其命名为T或者其他):
public class ArrayList<E> extends ... {
public E get(int index) { ... }
public boolean add(E element) { ... }
// other methods...
}
Run Code Online (Sandbox Code Playgroud)
现在,当您创建此类的实例时,您可以定义类型参数的具体值,例如String(E通常可以评估为您想要的任何类型):
ArrayList<String> stringList = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)
从现在开始,所有的Es的"改为"通过String为stringList可变的,所以你可以只添加字符串到它,只有从它那里得到的字符串.编译器会检查您是否错误地添加了另一种类型的对象:
stringList.add(Integer.valueOf(1));
// compile error - cannot add Integer to ArrayList of Strings
Run Code Online (Sandbox Code Playgroud)
但是,由于泛型被添加到Java 5中,因此仍然可以编写没有它们的代码以实现向后兼容性.所以你可以写:
ArrayList list = new ArrayList();
Run Code Online (Sandbox Code Playgroud)
但是你失去了所有类型检查的好处.E方法签名中的Objects 变得简单.
list.add(Integer.valueOf(42)); // adding an Integer
list.add("aaa"); // adding a String
Object something = list.get(0); // unknown type of returned object, need to cast
Integer i0 = (Integer) something; // this unsafe cast works...
Integer i1 = (Integer) list.get(1); // but this fails with a ClassCastException
// because you cannot cast a String to Integer
Run Code Online (Sandbox Code Playgroud)
使用原始类型(省略类型参数的泛型类型)不安全的事实是您获得警告的原因.而不仅仅是ArrayList,使用ArrayList<String>或者ArrayList<Integer>不管你的类型items.
ArrayList 中存储了哪些类型的对象?您需要将其添加到声明中。总是如此
ArrayList<Type>
Run Code Online (Sandbox Code Playgroud)
因此,如果它是 JSONObjects 列表,您可以输入
ArrayList<JSONObject>
Run Code Online (Sandbox Code Playgroud)
希望有帮助。
| 归档时间: |
|
| 查看次数: |
70549 次 |
| 最近记录: |