简体   繁体   中英

What could be a more efficient replacement of this data structure?

I have a class named Pair which is constructed to hold pairs of integer values.

public class Pair implements Comparable<Pair> 
{

    public int word1;//1st integer of the pair
    public int word2;//2nd integer of the pair

    public Pair(int w1, int w2) 
    {
        word1 = w1;
        word2 = w2;
    }

    @Override
    public int compareTo(Pair input) 
    {
        if (input.word1 == word1) 
        {
            if (input.word2 == word2) 
                return 0;
            else if (input.word2 < word2)
                return 1;
            else
                return -1;

        } 
        else if (input.word1 == word2) 
        {
            if (input.word2 == word1)
                return 0;
            else if (input.word2 < word1)
                return 1;
            else
                return -1;

        } 
        else if (input.word1 > word1)
            return -1;

        return 1;
    }

} 

What can I use as a better and efficient way of storing my integer pairs instead of this class? Can I use an array list or something? would that be more efficient or not?

A typical pattern to implement lexicographical comparison, this is what you seem trying to achieve, is:

int r; 

r = Integer.compare(word1, input.word1);

if(r==0) return r;

return Integer.compare(word2, input.word2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM