如何更新java中arraylist中的数组中的元素

时间:2012-02-11 05:46:34

标签: java arrays arraylist

我在Java中创建了一个ArrayList,并在其中添加了一些整数和一些双精度数,然后我添加了一个整数数组和一个双精度数组。现在我已经更改了数组中其中一个双精度值,我想更新它。但是,我无法为它提供确切的语法,因为它是ArrayList中数组中的一个位置。

更具体地说,我有

ArrayList<Patch> patches; 
patches = new ArrayList<Patch>();  //the ArrayList of patches

int[] VisPatch;  //the array of integers that keeps track of the patchID of the visible patches
double[] formFactor;  //the array of doubles that keeps track of the formFactor for the visible patches

//these are brought in from a file using a scanner
int patchID = fin.nextInt(); //the patch number for each patch in the file
double emissionPower = fin.nextDouble();  //the emission power of the individual patch
double reflectance = fin.nextDouble();  //the reflectance of the individual patch
int numVisPatch = fin.nextInt();  //the number of patches that are 'visible' to this particular patch

//initialize the arrays that hold the visible patch parameters
VisPatch = new int[numVisPatch];
formFactor = new double[numVisPatch];

for(int i=0; i<numVisPatch; i++){
    VisPatch[i] = fin.nextInt(); //brought in from file
    formFactor[i] = fin.nextDouble();
}//end for loop

//create a new patch object from the numbers read in
patches.add(new Patch(emissionPower, reflectance, numVisPatch, VisPatch, formFactor));

//get the first visible patch in the VisPatch array
int adjacentPatchID = patches.get(maxKeyIndex).VisPatch[k]; //maxKeyIndex has been declared, and yes, we're in a for loop that uses k

//do some math on the emissionPower
double increment = 2;
double newEmissionPower = patches.get(adjacentPatchID).emissionPower + increment;

//now update the emission power of the patch
ummm...

我试过

patches.set(adjacentPatchID, newEmissionPower);

patches.set(get(adjacentPatchID).emissionPower, newEmissionPower);

patches.set(adjacentPatchID.emissionPower, newEmissionPower);

但我的IDE(我正在使用Eclipse)只是在所有内容中放了一堆红色的波浪线,并说我不知道​​我在说什么(主要是因为我没有)。

2 个答案:

答案 0 :(得分:0)

您已创建ArrayList;这是一个List。含义......事物列表(在您的情况下,Patch个对象)。您需要通过特定索引(ArrayList的一项功能)访问它,或者遍历它以找到您要查找的内容。

JavaDocs是你的朋友:http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

与Oracle教程一样:http://docs.oracle.com/javase/tutorial/collections/interfaces/list.html

答案 1 :(得分:0)

我假设您要更新的内容位于Patch类,而不是补丁的列表

你希望按ID获取补丁(假设你的&#34; id&#34;在这种情况下是它在列表中的位置;如果没有,你可以考虑使用{{1然后改变它:

Map<Integer, Patch>