Issue
I have a function that takes in an array
of Sets
, and I want to iterate through them.
In the implementation below f1
, I was able to successfully run it.
public static void f1(Set<Integer>[] sets){
for (int i = 0; i < sets.length; i++) {
for (int j : sets[i]) {
System.out.println(j);
}
}
}
However, when I try the java shorthand for loop below in f2
, it throws an error: error: incompatible types: Object cannot be converted to int for (int i : s) {
public static void f2(Set<Integer>[] sets){
for (Set s : sets) {
for (int i : s) {
System.out.println(i);
}
}
}
I wasn't sure why it doesn't work, since as I am iterating through the array, while each element is a set I create a dummy variable s
to refer to that set, then I create another dummy variable i
for an int. The error message suggests maybe I need a cast of some sort for int
, but I don't quite see where, since int i
is already an integer.
Solution
When you write Set
without <>
for java this means you don't care about generic type of Set, this is close enough to Set<?>
or Set<Object>
, so, java will not even try to determine the generic type. If you wish to write the short code without <>
you can use var
in your case:
public static void f2(Set<Integer>[] sets){
for (var s : sets) {
for (int i : s) {
System.out.println(i);
}
}
}
Works for java 10+
Answered By - SemperAnte
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.