In order to save an ArrayList with payments done by one member I want to change the List of Payment ID's into a string, so I created the following method:
public String fromArraytoString(ArrayList items){
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
return json.toString();
}
But I get the following warning:
ArrayList is a raw type. References to generic type ArrayList should be parameterized
Can anyone explain me why?
解决方案
You definitely should read this tutorial on Java generics:
http://docs.oracle.com/javase/tutorial/java/generics/
In a nutshell:
Many Java classes and types (called generic classes or generic types), typically collections, have so called type parameters, such as E in ArrayList (E is just an arbitrary chosen name, other classes name it as T or whatever):
public class ArrayList extends ... {
public E get(int index) { ... }
public boolean add(E element) { ... }
// other methods...
}
Now, when you create an instance of such class, you define a concrete value of the type parameter, for example String (E can usually be evaluated to whatever type you want):
ArrayList stringList = new ArrayList();
From now on, all the Es are "replaced" by String for the stringList variable, so you can add only Strings to it and get only Strings from it. The compiler checks for you that you don't mistakenly add an object of another type:
stringList.add(Integer.valueOf(1));
// compile error - cannot add Integer to ArrayList of Strings
However, because generics were added to Java 5, it is still possible to write code without them for backwards compatibility. So you can write:
ArrayList list = new ArrayList();
But you lose all the type checking benefits. Es in method signatures become simply 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
The fact that using a raw type (that is a generic type with its type parameters omitted) is unsafe, is the reason for the warning you've got. Instead of just ArrayList, use ArrayList or ArrayList or whatever the type of your items is.