简体   繁体   中英

creating a hashmap for a particular condition in java

I am trying to create a hashmap of:

{Integer, List<Integer>}.

For example, I have the following set: Numbers { 0,1,3,4,5 0,1,4,5,6 0,1,6,7,8 1,2,5,6,7 1,2,4,5,6 }

I need to create a hashmap with the first value in the above set as key while adding the values into lists like so: hashmap = [0 = {1,3,4,5}, {1,4,5,6}, {1,6,7,8}] [1 = {2,5,6,7}, {2,4,5,6}]

and so on.

I traverse the set. If the first value is different from the previous, I need to create a new list and start storing. Otherwise I need to add values to the previously created list.

I am having trouble creating the new list. If I do something like this:

    int prev = 0;
    for(Number n : Numbers)
    {
        int current = n;
        if(prev_first != current)
        {
            List<Integer> l = new Arraylist<>();
            hashmap.out(current, l);
            l.add(n);
        }
        else
        {
            l.add(n);
        }
    }

The trouble is the compiler cannot see the list 'l' and says that it may not be initialised for the else condition.

How can I resolve this?

Thanks and regards, Smitha.

You are creating the list in the if statement. Therefore you cannot access the list from the else statement. Just create the list before the if statement and the compiler will stop complaining.

Basically l only exists in the if -Condition. else does not see it. Try:

int prev = 0;
for(Number n : Numbers)
{
    int current = n;
    List<Integer> l = new Arraylist<>();
    if(prev_first != current)
    {            
        hashmap.out(current, l);
        l.add(n);
    }
    else
    {
        l.add(n);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM