2012-11-23 92 views
0

我是Java初學者,我想問一下關於Java編寫通用代碼的傳統的一些話。我在下面的代碼中編寫了用於將項目推入通用排序集合的幫助類,並且我想知道它被接受了嗎?或者我應該擴展一些基類的集合?或者以其他方式歡迎更多Java?如何在Java中編寫標準對象的泛型擴展?

package com.rkovalev.Helper; 

import java.util.Comparator; 
import java.util.List; 

public abstract class ListExtensions { 
    public static <T> void addOnCompare(List<T> collection, T item, Comparator<T> comparator) { 
     synchronized(collection) { 
      int i = 0; 
      int size = collection.size(); 
      if (size == 1) { 
       int diff = comparator.compare(item, collection.get(0)); 
       switch(diff) { 
       case 1: i++; break; 
       default: break; 
       } 
      } else { 
       int range = size - 1; 
       i = size/2; 
       int left = 0; 
       int right = range; 
       while(true) { 
        if (i <= 0) { i = 0; break; } 
        if (i > range) { i = range; break; } 
        int diff = comparator.compare(item, collection.get(i)); 
        if (diff == 0) break; 
        else { 
         if (diff == -1) right = i; 
         if (diff == 1) left = i; 
         int near = i + diff; 
         if (near < 0) { i = 0; break; } 
         if (near > range) { i = range + 1; break; } 
         int diff_near = comparator.compare(item, collection.get(near)); 
         if (diff_near == 0) { i = diff_near; break; } 
         if (diff_near == diff) { 
          int step = (right-left)/2; 
          if (step == 0) step = 1; 
          switch(diff){ 
          case -1: 
           right = i; 
           i = i - step; break; 
          case 1: 
           left = i; 
           i = i + step; break; 
          } 
         } else if (diff > diff_near) { 
          i = near; break; 
         } else { break; }   
        } 
       } 
      } 
     collection.add(i, item); 
     } 
    } 
} 
+1

如果你要求代碼審查,請考慮發佈到http://codereview.stackexchange.com/。 –

回答

2

如果你想使可用於所有集合類額外的「通用」的功能,然後在「助手」類寫的功能的靜態方法是正確的道路要走。

將該方法添加到現有集合類的基類中將不起作用。這將需要修改標準的Java類庫,並且沒有人在他們的正確思想中這樣做。 (這在技術上是可行的,但是你會爲你的代碼創建一個可移植的噩夢,如果你使用與你的代碼相關的商標術語「Java」,更不用提法律問題了。)