如何在java中为标准对象编写泛型扩展?

时间:2012-11-23 12:32:03

标签: java generics

我是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 个答案:

答案 0 :(得分:2)

如果您想为所有集合类提供额外的“通用”功能,那么在“帮助程序”类中将该功能作为静态方法编写是正确的方法。

将方法添加到现有集合类的基类将不起作用。这将需要修改标准的Java类库,而没有正确思想的人会这样做。 (这在技术上是可行的,但你会为你的代码创建一个可移植性的噩梦。如果你使用与你的代码相关的商标术语“Java”,更不用说法律问题了。)