简体   繁体   中英

Why Doesn't compareTo() work?

I have two ArrayLists:

ArrayList<String> testList = new ArrayList<>();
ArrayList<String> wordList = new ArrayList<>();

They are being passed into a method:

public static void binSearch(ArrayList a1, ArrayList a2)

Inside the method, I want to compare the strings between the two ArrayList:

a1.get(i).compareTo(a2.get(newEnd / 2))

However, I received an error message:

cannot find symbol
symbol: method compareTo(Object)
location: class Object

I heard some people say that I need to implements/extends Comparable, but it seems like some people are just doing fine with the method without importing/implementing/extending anything.

Do not use raw types. Declare your binSearch this way:

public static void binSearch(ArrayList<String> a1, ArrayList<String> a2)

Or if you want to support any Comparable types introduce generic type variable:

public static <T extends Comparable<? super T>> void binSearch(List<T> a1, List<T> a2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM