I have a problem to get list including many index as a result of getting key value. I have an error in my code.
My City class shown below.
public class City implements Serializable{
private String cityName;
private String countryName;
...
}
My Arraylist contains city names and its country Names as shown below.
Shanghai, China
...
...
As Arraylist is very large size like 50000, I apply binary Search to search any character or word in the list.
I want to search any character or Word which is sensitive to Uppercase or lowercase and retrieve back their indexs.
How can I do this process?
The code run according to the defined characher, character string or word shown below.
Sample Examples
Enter the word of character which I want to search : W
Enter the word of character which I want to search : Sha
Enter the word of character which I want to search : Shanghai
Here is my code snippet shown below.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the word of character which I want to search : ");
String charWord = scanner.nextLine();
System.out.println("Search " + charWord);
Integer[] index = BinarySearch.binarySearch(cities, charWord);
System.out.println(index.toString());
public static Integer[] binarySearch( ArrayList<City> list, String key ) {
Comparable comp = (Comparable)key;
List<Integer> arrlist = new ArrayList<Integer>();
Integer arr[] = null;
int res = -1, min = 0, max = list.size() - 1, pos;
while( ( min <= max ) && ( res == -1 ) ) {
pos = (min + max) / 2;
int comparison = comp.compareTo(key.contains(list.get(pos).getCityName()));
if( comparison == 0) {
res = pos;
arrlist.add(res);
}
else if( comparison < 0)
max = pos - 1;
else
min = pos + 1;
}
return arrlist.toArray(arr);
}
comp.compareTo(key.contains(list.get(pos).getCityName()));mean? are you looking for an exact match or some percentage of match like Shanghai and Shangall for e.g.? If the latter is the case you need to do a nearest match and you need to write a separate function to compare two strings and give you a measure of equality.containsonly tells you if a string is present in another string. Also I believe a data structure like Ternary Search Trie would also be more efficient in that case.W? or containsW? or ends withW? In any case it seems you are looking for something like prefix match in a set of strings for which a trie is more suited I believe.