Java 有什么能更有效地替代这种数据结构?
我有一个名为Pair的类,它被构造来保存整数值对Java 有什么能更有效地替代这种数据结构?,java,data-structures,performance,Java,Data Structures,Performance,我有一个名为Pair的类,它被构造来保存整数值对 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 =
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;
}
}
公共类对实现了可比较的
{
public int word1;//该对的第一个整数
public int word2;//该对的第二个整数
公共线对(int w1,int w2)
{
字1=w1;
word2=w2;
}
@凌驾
公共整数比较(成对输入)
{
if(input.word1==word1)
{
if(input.word2==word2)
返回0;
else if(input.word2word1)
返回-1;
返回1;
}
}
我可以用什么来代替这个类来存储整数对呢?我可以使用数组列表还是什么?这是否更有效?实现词典比较的一种典型模式是:
int r;
r = Integer.compare(word1, input.word1);
if(r==0) return r;
return Integer.compare(word2, input.word2);
一个直接的改进是将您的成员命名为min和max。然后,在构造函数中,总是将较小的值存储在min中,将较大的值存储在max中。您的compareTo将变得更小。在这一点之后,如果不知道类的用途,就无法回答效率问题。@Chandranshu-不仅如此,他目前正在打破
可比性
,因为它不是自反性的-排序不再保证稳定。@Clockwork Muse-+1注意到这一点。我甚至没有读过整个比较法!我认为您应该将此代码带到以获取更多审阅注释。