Pergunta

I am kinda new to Java, and I am trying to write a function that maps all element indexes from an ArrayList into a HashMap, so I can easily see the indexes of duplicate elements.

The code below works , but when I try to print the values using the second for, it shows completely different results!

Example:

60 [40, 64]

What the 2nd for shows

60 [64]

more numbers

60 [64]

HashMap<Integer,ArrayList<Integer>> table= new HashMap<Integer,ArrayList<Integer>>();

//checking all items in an ArrayList a 
//and putting their index in a hashTable
for(int i=0; i<a.size(); i++){

        ArrayList<Integer> indexes = new ArrayList<Integer>();
        indexes.add(i);

        for(int j=i+1; j<a.size(); j++){

            //are the items equal?
            if(a.get(j).equals(a.get(i))){
                indexes.add(j);
            }       

        }
        //put in the HashMap
        table.put(a.get(i), indexes);
        System.out.println(a.get(i) + " " +table.get((a.get(i))));

    }
   //shows completely different results!
    for(int ix=1;ix<table.size();ix++)
        System.out.println(a.get(ix) + " " +table.get(a.get(ix)));
Foi útil?

Solução

Try this:

public static void main(String[] args) {
    List<Integer> input = Arrays.asList(60, 60, 1, 4, 5, 7, 60);

    Map<Integer, List<Integer>> result = new HashMap<>();

    for (int n = 0; n < input.size(); ++n) {
        List<Integer> list = result.get(input.get(n));

        if (list != null) {             
            list.add(n);
        } else {
            list = new ArrayList<>();
            list.add(n);
            result.put(input.get(n), list);
        }
    }

    System.out.println(result); // prints {1=[2], 4=[3], 5=[4], 7=[5], 60=[0, 1, 6]}
}

Outras dicas

But I don't get it...What did I do wrong? As far as I see, my code is really inefficient compared to yours, but shouldn't it do the same thing?

Well no. In addition to being inefficient, your version has a significant bug.

Lets take your example input {60, 60, 1, 4, 5, 6, 7, 60}.

First iteration the loop, you build a list containing {0, 1, 7} and put it into the map so that we have map containing{ 60 -> {0, 1, 7} }`

Second iteration of the loop, we build a list containing {1, 7} and put it into the map. But this of course replaces the original (correct) list for 60 ... and we end up with { 60 -> {1, 7} }

And so on. In short, your version will end up producing a map that maps from the values to a list containing just the last index of that value.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top