问题
I have a multi-dimensional array of string. I am willing to convert it into some collection type, so that I can add, remove and insert elements according my wish. In array I can not remove element at particular position.
I need such collection in which I can remove data at particular position, also able to add data at any position.
Also dont forget I have multi-dimension array, so the collection should also able to store multidimensional data.
Which collection will be suitable for my requirments?
回答1:
ArrayList should do what you need. For instance:
List<List<String>> stringList = new ArrayList<List<String>>(); //A List to store a list of strings
or...
List<String[]> myNumberList = new ArrayList<List<String[]>(); //A List to store arrays of Strings.
回答2:
Are you sure you have Multi-Dimensional array? Because I look for your sample data ("yes","abbbc") it is for One-Dimensional array. But let me give you an example:
// This example for multi-dimensional array of string
String[][] arrays = new String[][]{{"aa", "bb", "cc"}, {"dd", "ee", "ff"}};
Map<Integer, List<String>> map = new HashMap<>();
List<String> list;
for(int i = 0; i < arrays.length; i++) {
list = Arrays.asList(arrays[i]);
map.put(i, list);
}
for(int i = 0; i < map.size(); i++) {
for(int j = 0; j < map.get(i).size(); j++) {
System.out.println(map.get(i).get(j));
}
}
// This example for one-dimensional array of string
String[] arr = new String[] {"aa", "bb"};
List<String> listArr = Arrays.asList(arr);
for(String str : listArr) {
System.out.println(str);
}
For Multi-Dimensional array I'm using HashMap and for One-Dimensional array I'm using ArrayList. Read this if you still don't understand between those two. And please Correct Me If I'm Wrong
回答3:
As with any problem, you have multiple options for data-structures and you have to make a design decision based on their trade-offs (time, space).
Two data structures that immediately come to mind are ArrayList and LinkedList. With a LinkedList you can insert and remove an element from any position in O(1) constant time. With an ArrayList this would be linear time O(n).
However, accessing an element in an ArrayList is constant time (you can index into it). Whereas, normally with a LinkedList you would need to traverse through it. This problem in LinkedList though can be avoided though by hashing each of the elements, so you can find a particular node in a linked list in amortized constant time. Of course, having a hash and a linked list is a speedier solution than an array though there is more overhead in terms of space.
For more information on these data-structures: Arrays, Linked Lists, Hash Tables Java implementations of these data structures: ArrayList, LinkedList, Hash table
来源:https://stackoverflow.com/questions/10477407/which-collection-is-better-to-store-data-from-multi-dimensional-array