开发者

How to compare to abstract enums?

开发者 https://www.devze.com 2023-03-29 00:54 出处:网络
I\'m working on a searching / organizational algorithm. I use multiple enum\'s to define every piece of data that I would want to organize. For example:

I'm working on a searching / organizational algorithm. I use multiple enum's to define every piece of data that I would want to organize. For example:

enum CarType implements SearchFactor {
    CAR, SUV, TRUCK, SEMI, LIMO;
    @Override public SearchFactor getSearchFactor() { return this; }
}

and

enum PaintColor implements SearchFactor {
    BLACK, WHITE, BLUE, GRAY, RED;
    @Override public SearchFactor getSearchFactor() { return this; }
}

where SearchFactor is:

interface SearchFactor { }

and a sample data class would be:

class Vehicle {
    CarType type = CarType.CAR;
    PaintColor color = PaintColor.BLA开发者_开发知识库CK;
}

Now for the organization part, I just create an array of included SearchFactor's and add the enum of what SearchFactor I would like the algorithm to follow. This is done by incrementally walking through an array of Vehicles and comparing the Vehicles type and color to the array of included SearchFactors. For example:

Vehicle[] getVehicleFromSearchFactor(SearchFactor[] factors) {
    ArrayList<Vehicle> factoredVehicles = new ArrayList<Vehicle>();
    for (Vehicle v : getListOfVehicles()) {
        for (SearchFactor f : factors) {
            if (v.type == f || v.color == f) {
                factoredVehicles.add(v);
                break;
            }
        }
    }
    return factoredVehicles;
}

Is this good practice? Is this too abstract?


What is the point of a getSearchFactor() method which only is implemented as return this?

It is not even used in your getVehicleFromSearchFactor method.

Other than this, why not. Just make sure that == is the right way to compare your search factors. For enums this is fine, but for other objects .equals(...) might be better ... or even .appliesTo(...) or such.

(Of course, your search in this way allows about no indexing, and has O(number of vehicles × number of search factors) time complexity.)


Agree with answer above re: "getSearchFactor()" method.

In addition to answer above, it seems to me this might be better handled through whatever persistence layer you might be using or some additional indexing technology such as Lucene/Solr.

0

精彩评论

暂无评论...
验证码 换一张
取 消