Reputation: 149
I have one problem of choosing which array use for this case. There are many arrays like list, colection, and others. I want to keep two numbers like this in array(numbers here is random): (many rows and 2 columns).
2, 4
4, 8
8, 7
...
But also have functionality with this array, easily take first array row and put it at the end. What can you suggest for me to use in this case?
p.s. im new so I want pick best option, thats why im here.
Upvotes: 1
Views: 79
Reputation: 68847
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.
Upvotes: 2
Reputation: 726489
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.
Upvotes: 1
Reputation: 17422
You should better create a class, say, 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; }
}
And then choose between ArrayList<Pair>
, HashSet<Pair>
, etc. depending on you particular needs.
Upvotes: 3