I don't understand why I'm having this errors and how to solve them, on the following code in mine MainActivity file. I've searched on Google but I can't relate the solutions to mine code. I have also passed -Xlint:unchecked to javac, but can't get any wiser either.
I'm pretty new to Android and Java programming and trying to solve any highlights in mine code.
Thanks in advance.
Unchecked assignment: 'java.util.ArrayList' to 'java.util.ArrayList' less... (Ctrl+F1) Signals places where an unchecked warning is issued by the compiler, for example:
void f(HashMap map) { map.put("key", "value"); } Hint: Pass -Xlint:unchecked to javac to get more details.
Unchecked call to 'ArrayList(Collection)' as a member of raw type 'java.util.ArrayList' less... (Ctrl+F1) Signals places where an unchecked warning is issued by the compiler, for example:
void f(HashMap map) { map.put("key", "value"); } Hint: Pass -Xlint:unchecked to javac to get more details.
private void readItems() {
File filesDir = getFilesDir();
File todoFile = new File(filesDir, "todo.txt");
try {
items = new ArrayList<>(FileUtils.readLines(todoFile));
} catch (IOException e) {
items = new ArrayList<>();
}
}
Root cause: You are using ArrayList
as a generics type in Java but do not specific a particular type for it. That why the compiler shows that warning.
So what happen when you do not specific a particular type for generics. Here is a scenario.
// You want this line contains only Integer.
List list = new ArrayList<>();
// 1. Warning when add new item.
list.add(1);
list.add(2);
list.add(3);
// 2. Must cast to Integer when using.
Integer number2 = (Integer) list.get(1);
// 3. Do not prevent developers from adding non-integer type, such as String, double, boolean etc.
list.add("Four");
list.add(true);
// 4. Might throws ClassCastException and make your app crashes.
Integer number = (Integer) list.get(4);
Solution: Specific or pass a particular type for a generic type inside angle brackets <>
.
// You want this line contains only Integer.
List<Integer> list = new ArrayList<>();
// If you want to declare variable first
List<Integer> items;
// Then initialize
items = new ArrayList<>();
// 1. No warning when add new item.
items.add(1);
list.add(2);
list.add(3);
// 2. No need to cast to Integer.
Integer number2 = list.get(1);
// 3. Prevent developers from adding non-integer type, such as String, double, boolean etc.
list.add("Four"); // Error when compile
list.add(true); // Error when compile
// 4. You cannot add non-integer type and no need to cast so ClassCastException never occurs.
Integer number = list.get(2);
There are many generics class built-in in Java such as List
, ArrayList
, Map
, HashMap
, Set
, HashSet
, etc...