有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

netbeans如何在java的linkhashmap中自动生成密钥

我用netbean在java中制作了这样的linkedhashmap

LinkedHashMap=新建LinkedHashMap()

 map.put(0, "one");
 map.put(1, "two");
 map.put(2, "three");

在上面的代码中,键(0,1,2)是自动生成的。 我尝试了不同的在线解决方案,但不起作用


共 (3) 个答案

  1. # 1 楼答案

    你可以使用map.size()

    map.put(map.size(), "one"); // map.size() returns 0
    map.put(map.size(), "two"); // map.size() returns 1
    map.put(map.size(), "three"); // map.size() returns 2
    ...
    
  2. # 2 楼答案

    public class Test {
    
        static int i = 0;
    
        public static void main(String[] args) {
    
            Map<Integer, String> map = new LinkedHashMap<>();
            map.put(getNext(), "One");
            map.put(getNext(), "Two");
            map.put(getNext(), "Three");
            map.forEach((key, value) -> System.out.println("Key = " + key + ", value = " + value));
        }
    
        static int getNext() {
            i = i+1;
            return i;
        }
    }
    
  3. # 3 楼答案

    public class Main {
        public static void main(String[] args) {
            Map<Integer, String> map = new LinkedHashMap<>();
            map.put(KeyGenerator.getNextKey(), "One");
            map.put(KeyGenerator.getNextKey(), "Two");
            map.put(KeyGenerator.getNextKey(), "Three");
            map.forEach((key, value) -> System.out.println("Key = " + key + ", value = " + value));
        }
    
        static class KeyGenerator {
            private static AtomicInteger key = new AtomicInteger(0);
            public static int getNextKey() {
                return key.getAndAdd(1);
            }
        }
    }