[关闭]
@w1024020103 2017-03-12T23:46:55.000000Z 字数 1732 阅读 494

Proj2 Catalog.java

CS61B


Catalog.java

屏幕快照 2017-03-09 下午8.45.22.png-75.2kB

For the first time I used HashMap to store the tables as values using String and Integer as key respectively.

  1. public class Catalog {
  2. private HashMap<String,Table> nameHash;
  3. private HashMap<Integer,Table> iDHash;
  4. public class Table{
  5. public String tableName;
  6. public String pkeyFieild;
  7. public DbFile tableFile;
  8. public Table(String name, String pkeyFieild, DbFile file){
  9. this.tableName = name;
  10. this.pkeyFieild = pkeyFieild;
  11. this.tableFile = file;
  12. }
  13. }
  14. /**
  15. * Constructor.
  16. * Creates a new, empty catalog.
  17. */
  18. public Catalog() {
  19. // some code goes here
  20. this.nameHash = new HashMap<>();
  21. this.iDHash = new HashMap<>();
  22. }

When implementing method like addTable(), I used put() method for HashMap for the fisrt time. Just use hashmap.put(key,value) to put a value to a key in a hashmap.

  1. public void addTable(DbFile file, String name, String pkeyField) {
  2. // some code goes here
  3. Table t = new Table(name, pkeyField, file);
  4. nameHash.put(name,t);
  5. iDHash.put(file.getId(),t);
  6. }

When implementing method like getDbFile(int tableid), I used get(key) method for HashMap. Just use hashmap.get(key) then you can get the corresponding value.

  1. public DbFile getDbFile(int tableid) throws NoSuchElementException {
  2. // some code goes here
  3. Table tableToGetDbFile = iDHash.get(tableid);
  4. if(tableToGetDbFile == null){
  5. throw new NoSuchElementException("the table doesn't exist");
  6. }else {
  7. return tableToGetDbFile.tableFile;
  8. }
  9. }

When writing tableIdIterator(), things become super easy for HashMap, because the key for HashMap data structure has to be a list or set that are iterable. So I can just return hashmap.keySet().iterator() to get an Iterator of hashmap's keys.

  1. public Iterator<Integer> tableIdIterator() {
  2. // some code goes here
  3. Set<Integer> keys = this.iDHash.keySet();
  4. return keys.iterator();
  5. }

Finally, there's a clear() method to delete all the info for a hashmap.

  1. /** Delete all tables from the catalog */
  2. public void clear() {
  3. // some code goes here
  4. this.iDHash.clear();
  5. this.nameHash.clear();
  6. }
  7. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注