java警告是原始类型,警告ArrayList是一种原始类型。对泛型类型ArrayList的引用< E>应该参数化...

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.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值