2013-07-26 26 views
-2

我必须在java中的一个数据结构中保存两个数字,但这两个数字的顺序很重要。这意味着,每当我称这些数字时,第一个号码是我的Nucleus,第二个号码是我的Satellite。我不知道应该使用哪种数据类型,如果我使用ArrayList,它将使用如此多的内存,我不需要这些内存。因为ArrayList的初始大小是10,但我只需要2.如果使用HashSet,我没有顺序。如何将ArrayList的大小减少到2?

ArrayList<int> array=new ArrayList<int>(2); 
+0

而这是你的问题吗?您发布的代码会创建一个大小为2的ArrayList,这是您标题中问题的答案。 – f1sh

+0

这些值是否以某种方式相关? –

+0

@ f1sh,ArrayList默认有10个大小,你不能减少它。但他想要的东西只能占用2个单位的数据 – Reddy

回答

1

为什么不简单Array []。

int[] data = new int[2]; 
int[0] = //nucleas 
int[1] == //satellite. 

但更重要的是你的问题没有作出任何感和空间/时间这一要求

0

您可以使用简单的数组中的Java

int[] anArray; 

// allocates memory for 2 integers 
anArray = new int[2]; 
+0

Java数组是不可变的。另外,OP不能有一个基元的ArrayList。 –

0

列表最好在那些使用当你不知道你的元素的数量的情况。但是,在你的情况,你知道,你只有2元,然后使用araay代替

int[] array = new int[2]; 

,并添加值

array[0] = <int_value>; 
array[1] = <int_value>; 
7

我实际上更倾向于这里的Object基础的解决方案;如果有任何代码可读性。

public class Atom 
{ 
    private int nucleus; 
    private int satellite; 

    public Atom(int nucleus, int satellite) 
    { 
     this.nucleus = nucleus; 
     this.satellite = satellite; 
    } 
} 

提到他们作为一个阶级的成员意味着你不必担心顺序,你可以存储为你在一个集合想要的。

List<Atom> atoms = new ArrayList<Atom>(); 
atoms.add(new Atom(4,1)); 

int nucleus = atoms.get(0).getNucleus(); 
// Assuming you've written your getter method. 

int satellite = atoms.get(0).getSatellite(); 
0

你的代码正是你需要在ArrayList中存储两个元素!

通过在ArrayList构造函数中传递2,可以创建长度为2的支持数组。接下来,您可以在不调整大小的情况下为其添加2个元素。但是,如果您将第三个元素添加到ArrayList,则将重新调整后备数组的大小。 ArrayList只是数组的一个很好的包装,所以使用它是因为它提供了比数组更多的功能。