0

我是 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);
        }
    }
}
4

1 回答 1

2

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

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

于 2012-11-23T12:56:56.783 回答