HASHMAP,关键礼物仍然给予"假"结果

时间:2016-11-22 10:10:01

标签: java hashmap

以下是我的代码,即使密钥存在,它也会返回false:

https://serallo.co.uk/highlight.php

}

在文件中输入数据:
1233
1233
1234

结果应该是
1
2
1

但每次进入else循环并且结果是
1
1
1

我正在尝试使用HASHMAP,因为我正在创建自己的索引。

2 个答案:

答案 0 :(得分:0)

这样的事情应该有效。但是Haven没试过它。

public class SequenceNumber {

 public static int getSequenceNumber (String TcOrderId, Map<String, Integer> map){  
    if(!map.contains(TcOrderId)){
        map.put(TcOrderId, 0);
    }

    map.put(TcOrderId, map.get(TcOrderId)+1);
    return map.get(TcOrderId);
}

public static void main(String[] args) throws IOException {

    String sCurrentLine;
    BufferedReader br = null;
    Map<String, Integer> map = new HashMap<String, Integer>();
    try {
        br = new BufferedReader(new FileReader("C:\\Users\\BongAn\\Desktop\\Package\\testing.txt"));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    {
        while ((sCurrentLine = br.readLine()) != null) {
            //String orderid = sCurrentLine.substring(0, 6);
            System.out.println("reading line " +sCurrentLine);
            int seqvalue = getSequenceNumber(sCurrentLine, map);
            System.out.println("seqvalue "+seqvalue);
        }

    }

答案 1 :(得分:0)

每次调用getSequenceNumber函数时,在CODE中都会创建新的HashMap。我相信这不是你想要的东西。

为了避免这种情况 - 你可以简单地将Map<String, Integer> map = new HashMap<String, Integer>();移到课堂上。由于函数getSequenceNumber是一个静态函数 - 您需要将变量设置为static。希望这会有所帮助。

<强>段:

public class SequenceNumber {

 // PUT STATIC VARIABLE HERE:
 static Map<String, Integer> map = new HashMap<String, Integer>();  

 public static int getSequenceNumber (String TcOrderId){

    // Create a hash map to set key values pair.
    // (REMOVE) Map<String, Integer> map = new HashMap<String, Integer>();**  
    int i= 1;

    // check if hashmap contains the key.
  ...
  }
...
}

另一种选择

(也许更好)是避免静态函数和变量并创建SequenceNumber对象的实例。这样你就可以分别保留几个不同的实例编号。

简单摘要:

public class SequenceNumber {

 // Your hashmap here:
 Map<String, Integer> map = new HashMap<String, Integer>();

 public int getSequenceNumber (String TcOrderId) {
  // ...
 }

public static void main(String[] args) throws IOException {

    // Instance of SequenceNumber object:
    SequenceNumber sequenceNumber = new SequenceNumber();

    String sCurrentLine;
    BufferedReader br = null;

    // ...
        while ((sCurrentLine = br.readLine()) != null) {
            //String orderid = sCurrentLine.substring(0, 6);
            System.out.println("reading line " +sCurrentLine);
            int seqvalue = sequenceNumber.getSequenceNumber(sCurrentLine);
            System.out.println("seqvalue "+seqvalue);
        }
    // ...
    }
}