問題描述
java ‑ 如何在java中使用某些特定索引將值存儲到arraylist中 (how to store value into arraylist with some specific index in java)
我有價值列表,例如
0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.10, 0.11, 0.12< /p>
我想將它存儲到具有特定索引的 ArrayList
中
0.1, 0.2, 0.3, = = 索引 1
0.4, 0.5, 0.6, == 索引 2
0.7, 0.8, 0.9, == 索引3
0.10, 0.11, 0.12, == 索引 4
謝謝
參考解法
方法 1:
ArrayList[][] array = {{0.1,0.2,0.3},{0.4,0.5,0.6},{0.7,0.8,0.9},{0.10,0.11,0.12}}
This is a multi‑dimensional array
To set values:
array[0][0] = 0.1;
array[0][1] = 0.2;
array[1][0] = 0.4;
array[1][1] = 0.5;
...ect
Also see How to create a Multidimensional ArrayList in Java?
方法 2:
you use array List and HaspMap for you requirement
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
ArrayList<Double> list = new ArrayList<Double>();
Map<String, ArrayList<Double>> map = new HashMap<String, ArrayList<Double>>();
list.add(0.1);
list.add(0.2);
map.put("key", list);
System.out.println(map.get("key").get(0));
}
}
方法 3:
In an ArrayList<Double>
a single index can have a single value.
If you want to store more than one value try using a ArrayList<ArrayList<Double>>
.
If you want to store it in an index use .set(index, value)
ArrayList<Double> list = new ArrayList<>();
list.add(0.1);
list.add(0.2);
list.add(0.3);
ArrayList<ArrayList<Double>> mainList = new ArrayList();
mainList.set(0, list);
From your list I see that 3 values make a list.
double []values = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.10, 0.11, 0.12};
ArrayList<ArrayList<Double>> mainList = new ArrayList();
int k = 0;
for(int i = 0; i < values.length; i += 3)
{
ArrayList<Double> list = new ArrayList();
list.add(values[i]);
list.add(values[i + 1]);
list.add(values[i + 2]);
mainList.set(k ++, list);
}
方法 4:
In arrayList you can't keep multiple value in same index, it just doesn't work that way.
Based on your requirement, i think, you can design the data structure in two way ‑
1. Map
Map<Integer, List<Double>>
a map keeping index as key, and list of the items as value. Thus keep (1, [0.1, 0.2, 0.3]) means 1 index as key and corresponding list as value
2. List of User Defined Object
class IndexValue {
int index;
double value;
IndexValue(int index, double value) {
this.index = index;
this.value = value;
}
}
List<IndexValue> indexValueList = new ArrayList<>();
indexValueList.add(new IndexValue(1, .1));
indexValueList.add(new IndexValue(1, .2));
indexValueList.add(new IndexValue(1, .3));
(by Putra Nurfajar、JavaFox、Kumaresan Perumal、Uma Kanth、shakhawat)