关于我的程序的一些信息,我实现了一个带有单独链接的哈希表来处理冲突。
class TableInput{
Object key;
Object value;
TableInput(Object key, Object value){
this.key = key;
this.value = value;
}
}
abstract class HashTable {
protected TableInput[] tableInput;
protected int size;
HashTable (int size) {
this.size = size;
tableInput = new TableInput[size];
for (int i = 0; i <= size - 1; i++){
tableInput[i] = null;
}
}
abstract int hash(Object key);
public abstract void insert(Object key, Object value);
public abstract Object retrieve(Object key);
}
class ChainedTableInput extends TableInput {
ChainedTableInput(Object key, Object value){
super(key, value);
this.next = null;
}
ChainedTableInput next;
}
class ChainedHashTable extends HashTable {
ChainedHashTable(int size) {
super(size);
// TODO Auto-generated constructor stub
}
public int hash(Object key){
return key.hashCode() % size;
}
public Object retrieve(Object key){
ChainedTableInput p;
p = (ChainedTableInput) tableInput[hash(key)];
while(p != null && !p.key.equals(key)){
p = p.next;
}
if (p != null){
return p.value;
}
else {
return null;
}
}
public void insert(Object key, Object value){
ChainedTableInput entry = new ChainedTableInput(key, value);
int k = hash(key);
ChainedTableInput p = (ChainedTableInput) tableInput[k];
if (p == null){
tableInput[k] = entry;
return;
}
while(!p.key.equals(key) && p.next != null){
p = p.next;
}
if (!p.key.equals(key)){
p.next = entry;
}
}
public double distance(Object key1, Object key2){
final int R = 6373;
Double lat1 = Double.parseDouble(Object);
}
}
现在我有一个包含城市名称,纬度和经度的csv文件。我需要从命令行参数中读取csv文件,并将城市名称作为哈希表中的键输入,输入纬度和经度作为值。我的问题是如何读取csv文件并将数据分成要放入哈希表的键和值对象?
答案 0 :(得分:0)
像这样 -
String csvFilePath = args[0];
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
HashTable chainedHashTable = new ChainedHashTable(100);
try {
br = new BufferedReader(new FileReader(csvFilePath));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] cityRow = line.split(cvsSplitBy);
String cityName = cityRow[0];
Double latitude = Double.parseDouble(cityRow[1]);
Double longitude = Double.parseDouble(cityRow[2]);
Coordinate coordinate = new Cordinate(latitude, longitude);
chainedHashTable.insert(cityName, coordinate);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormateException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Coordinate {
double latitude;
double longitude;
Coordinate (double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
// Other setters and getters
}