在这种情况下,我有一个选择使用哪个数组的问题。有许多数组,如列表、集合等。我想在数组中保留两个这样的数字(这里的数字是随机的):(多行和 2 列)。
2, 4
4, 8
8, 7
...
但也有这个数组的功能,很容易把第一个数组行放在最后。你能建议我在这种情况下使用什么?
ps 我是新人,所以我想选择最好的选择,这就是我在这里的原因。
您应该更好地创建一个类,例如Pair
:
class Pair {
private int i1;
private int i2;
public Pair(int i1, int i2) { this.i1 = i1; this.i2 = i2; }
public int getI1() { return i1; }
public int getI2() { return i2; }
}
然后根据您的特定需要在 、 等ArrayList<Pair>
之间进行选择。HashSet<Pair>
Depends on what you mean by saying easily. Easy for programming or high performance.
Since you are new, I guess you are looking for the first one. I would stick with an ArrayList<Integer>
or an ArrayList<Pair<Integer, Integer>>
, where Pair is a custom class like this:
public class Pair<A, B>
{
public Pair(A a, B b) { this.a = a; this.b = b; }
public A a;
public B b;
}
Then use like this:
List<Pair<Integer, Integer>> list = new ArrayList<Pair<Integer, Integer>>();
list.add(new Pair<Integer, Integer>(3, 5));
list.add(new Pair<Integer, Integer>(7, 1));
// now take the first and put it at the end:
list.add(list.remove(0));
Edit: If performance of moving the first element to the end is the bottleneck and you want this to go fast, well, then use a LinkedList. This will be an O(1) operation, whereas doing it with an ArrayList, it will be a O(n) operation.
First, you are talking about collections, not arrays: array is one specific kind of collection, and the most primitive one at that. You should use arrays directly when the number of elements in a collection is known at the time the collection is created, and never changes after that.
If your requirement is to remove an element from the beginning of a collection and inserting it at the end, then you should either use a Queue<T>
or a LinkedList<T>
, and make an object that represents the pair of numbers its generic type argument. These data structures are optimized for quick insertion and removal from the ends.