Java – maps strings to integers

The simplest method in Java is to map a string (Java string) to a (positive) integer (Java int)

>Are equal strings mapped to equal integers, and > different strings mapped to different integers?

Therefore, it is similar to hashcode (), but different strings are required to produce different integers So, in a sense, it will be a hascode () without collision possibility

An obvious solution will maintain a mapping table from string to integer, and a counter to ensure that the new string is assigned a new integer I'm thinking about how this problem is usually solved It is also interesting to extend it to other objects rather than strings

Solution

This is impossible to achieve without any restrictions, just because there are more possible strings than integers, so you will eventually run out of numbers

The solution can only be used if the number of available strings is limited Then you can use a simple counter This is a simple implementation that can use all (2 ^ 32 = 4294967296 different strings) It doesn't matter. It uses a lot of memory

import java.util.HashMap;
import java.util.Map;

public class StringToInt {

    private Map<String,Integer> map;

    private int counter = Integer.MIN_VALUE;

    public StringToInt() {
        map = new HashMap<String,Integer>();
    }

    public int toInt(String s) {
        Integer i = map.get(s);
        if (i == null) {
            map.put(s,counter);
            i = counter;
            ++counter;
        }
        return i;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>