H
hiwa
In the below code, argument type of compare() method is declared
as String. However, compiler emits the error:
IndexSort.java:25: cannot resolve symbol
symbol: method indexOf(String)
location class java.lang.Object
Java generics is very hard to master except the top level shallowest
user layer. Could someone help writing a String specific Comparator
class properly?
---------------------------------------------
01: import java.util.*;
02:
03: public class IndexSort{
04:
05: public static void main(String[] args){
06:
07: String[] sa
08: = {"abasa", "dwapba", "oobaon", "balsa", "eglengelbao", "sveembat"};
09:
10: Arrays.sort(sa, new IndexComparator<String>("ba"));
11:
12: System.out.println(Arrays.deepToString(sa));
13: }
14:
15: static class IndexComparator<String> implements Comparator<String>{
16: String str;
17:
18: public IndexComparator(String subs){
19:
20: str = subs;
21: }
22:
23: public int compare(String o1, String o2){
24:
25: return o1.indexOf(str) - o2.indexOf(str);
26: }
27: }
28: }
----------------------------------
as String. However, compiler emits the error:
IndexSort.java:25: cannot resolve symbol
symbol: method indexOf(String)
location class java.lang.Object
Java generics is very hard to master except the top level shallowest
user layer. Could someone help writing a String specific Comparator
class properly?
---------------------------------------------
01: import java.util.*;
02:
03: public class IndexSort{
04:
05: public static void main(String[] args){
06:
07: String[] sa
08: = {"abasa", "dwapba", "oobaon", "balsa", "eglengelbao", "sveembat"};
09:
10: Arrays.sort(sa, new IndexComparator<String>("ba"));
11:
12: System.out.println(Arrays.deepToString(sa));
13: }
14:
15: static class IndexComparator<String> implements Comparator<String>{
16: String str;
17:
18: public IndexComparator(String subs){
19:
20: str = subs;
21: }
22:
23: public int compare(String o1, String o2){
24:
25: return o1.indexOf(str) - o2.indexOf(str);
26: }
27: }
28: }
----------------------------------