2016-11-28 32 views
0

因此,我試圖創建一個具有不同配置的數據類型類,具體取決於main中給出的列表大小。這是一個房屋列表的數據類型,這個想法是,如果房屋列表(大小)的數量大於1000,我會使用樹或AVL樹實現名爲SmartULS的數據類型。根據Java中給定列表的大小創建具有不同實現的數據類型類

另一方面,如果它小於1000,可以使用散列表來實現。這個想法是根據給定列表的大小,使排序/獲取/設置/刪除更快。

我到目前爲止工作了這一點,但它不工作:

public class houseListings<K,V> { 

    protected TreeMap<K,V> tree = new TreeMap<>(); 
    protected AbstractHashMap<K,V> hashMap = new AbstractHashMap<K,V>(); 

    public void setHouseListings(size){ 
     int threshold = 1000; 
     if (size >= threshold) { 
      map = new AbtractMap<K,V>(); 
     } 
     else 
      map = new TreeMap<K,V>(); 

    } 
} 
+0

將代碼重寫爲可以真正運行的東西,並更新您的問題。 –

+0

什麼是錯誤?另外,作爲一個方面說明,我認爲在'map = new AbtractMap();' –

回答

0

我想原因它不工作是因爲

  1. 你有錯別字在你的代碼
  2. 你正在使用錯誤的類型(如AbstractHashMap)。您應該使用HashMapTreeMap

現在,來選擇不同的策略「,你應該考慮使用strategy design pattern的理想方式。我已經編寫了一些代碼來幫助您可視化它。

public static void main(String... args) { 

     //... some code that reads/calculates threshold 

     DataVolumneStrategy strategy; 
     if (threshold >= 1000) { 
      strategy = new HighVolumeStrategy(); 
     } else { 
      strategy = new NormalStrategy(); 
     } 

     //use map 
     strategy.getMap(); 

    } 

    interface DataVolumneStrategy { 

     Map<K, V> getMap(); 

    } 

    static class NormalStrategy implements DataVolumneStrategy{ 

     @Override 
     public Map<K, V> getMap() { 
      return new HashMap<>(); 
     } 
    } 

    static class HighVolumeStrategy implements DataVolumneStrategy { 

     @Override 
     public Map<K, V> getMap() { 
      return new TreeMap<>(); 
     } 
    } 

希望這會有所幫助。

+0

'這一行有一個錯字,那麼我將在DataVolumeStrategy中使用get/set/remove等方法呢?我只是在這些方法中使用if語句來解決這個問題? – lesterpierson123

+0

@ lesterpierson123你指的是返回的'Map'的'get','put'方法嗎?如果是的話,這個策略只是爲了讓你按照你的需要適當地實現'Map'接口。一旦你有了,你可以在你的主要方法中以你想要的方式使用它。如果不是,你能否詳細說明你的問題。 –

相關問題