问题
as title says i want to know if exist any structure that can allows something like this:
key = 1 -> arrayList1 , arrayList2 , arrayList3...
someStructure.add(1,arrayList<1>);
someStructure.add(1,arrayList<2>);
someStructure.add(1,arrayList<3>);
IMPORTANT
the key has to remain the same for each list.
回答1:
You can roll your own by using a Map
Map<YourKeyClass, List<Data>> someStructure
= new HashMap<YourKeyClass, List<Data>>();
To your desired situation, looks like you need:
Map<YourKeyClass, List<List<Data>>> someStructure
= new HashMap<YourKeyClass, List<List<Data>>>();
Here's a kickoff example of the structure:
class MyMapOfList<K, V> {
Map<K, List<V>> innerMap;
public MyMapOfListOfList() {
innerMap = new HashMap<K, V>();
}
public void put(K key, V value) {
List<V> list = innerMap.get(key);
if (list == null) {
list = new ArrayList<V>();
innerMap.put(key, list);
}
list.add(value);
}
}
And you may use it like this:
MyMapOfList<String, List<Data>> myMapOfList;
If you don't like to add/maintain the List
s internally in the Map
, you could use a structure from third party library like MultiMap from Guava, which behaves more like you want/need.
More info:
- What does it mean to "program to an interface"?
回答2:
A HashMap<Key,Value>
would do it.
SSCCE:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Number {
public static void main(String[] args) {
try {
Map mMap = new HashMap();
mMap.put("PostgreSQL", "Free Open Source Enterprise Database");
mMap.put("DB2", "Enterprise Database , It's expensive");
mMap.put("Oracle", "Enterprise Database , It's expensive");
mMap.put("MySQL", "Free Open SourceDatabase");
Iterator iter = mMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
}
mMap.put("Oracle", "Enterprise Database , It's free now ! (hope)");
System.out.println("One day Oracle.. : " + mMap.get("Oracle"));
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
Source: http://www.mkyong.com/java/how-to-use-hashmap-tutorial-java/
来源:https://stackoverflow.com/questions/23582585/inserting-many-arraylist-inside-a-single-structure