Two-dimensional ArrayList array

Just a very small question ... It seems that I am facing a very difficult task: I need to understand the structure of the index, for example {42, someString}. I tried:

Object entry[][] = new Object[1][1];
ArrayList<Object> my_list = new ArrayList<Object>();

However, it looks weird. Isn't there a better, much simpler solution to just keep an integer and a string? I need to wrap the string search and return Integer ... so I thought Collections and ArrayLists are good friends in the Java API.

+3
source share
9 answers

Solution: use a card

Um, you might 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 search using

Integer result = map.get("Some String");

: Sun Java Tutorial > > Interfaces >


OP

, . , , ( ):

// 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);

:

for(final Object[] candidate : myList){
    if("Some String".equals(candidate[0])){
        System.out.println("Result: " + candidate[1]);
        break;
    }
}

, , . . .

+18

 public Class IntegerStringTuple {
    private Integer number;
    private String string;

    //setters and getters etc.
 }
+2

, .

Map<Integer, String> map = new HashMap<Integer, String>();

map.put(42, "someString");
String str = map.get(42);
+2

HashMap

Map<String,Integer> map = new HashMap<String,Integer>();
map.put("foo",42);
+1

?

Map<String,Object>
0

, Map

0

Map. .

Map<String, Integer> map = new HashMap<String, Integer>();
0

ArrayList, , .

0
    ArrayList arr1 = new ArrayList();
ArrayList arr2 = new ArrayList();
arr2.add(1);
arr2.add(2);
arr2.add(3);
arr1.add(arr2);

for(int i=0;i<arr1.size();i++){
    System.out.println("i:"+arr1.get(i));

    for(int j=0;j<((ArrayList)arr1.get(i)).size();j++){
    System.out.println("j:"+((ArrayList)arr1.get(i)).get(j));
    }
}

: i: [1, 2, 3]

j:1
j:2
j:3
0
source

Source: https://habr.com/ru/post/1785488/


All Articles