Java – 2D ArrayList
This is just a very small problem... I seem to have encountered too many complex problems: I have to implement an index structure like {42, somestring} I tried:
Object entry[][] = new Object[1][1]; ArrayList<Object> my_list = new ArrayList<Object>();
However, this seems strange Is there only a simpler solution to store some integers and strings? I need to search strings and return integers... So I think collections and ArrayLists are good friends in the Java API
Solution
Solution: use maps
Well, maybe you need a map?
Map<String,Integer> map = new HashMap<String,Integer>(); map.put("Some String",42); // or,more correctly: map.put("Some String",Integer.valueOf(42));
You can use it to search
Integer result = map.get("Some String");
Reference: Sun Java Tutorial > collection trail > interfaces > the map interface
Fix op code
By the way, the code in the problem is flawed If you want to use an object array list (you shouldn't), what would you do:
// single dimension,not multi-dimension Object[] entry = new Object[]{"Some String",Integer.valueOf(42)}; // use interface as variable,not implementation type // generic type is object array,not object List<Object[]> myList = new ArrayList<Object[]>(); // add array to list myList.add(entry);
Now you can search like this:
for(final Object[] candidate : myList){ if("Some String".equals(candidate[0])){ System.out.println("Result: " + candidate[1]); break; } }
However, this is for reference only, do not do so The collection framework contains solutions for almost all standard cases Use maps