本文介绍了不区分大小写的字符串作为HashMap键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用不区分大小写的字符串作为HashMap键,原因如下:

I would like to use case insensitive string as a HashMap key for the following reasons.


  • 在初始化过程中,用户定义了HashMap String

  • 在处理一个事件(在我的情况下是网络流量)的时候,我可能在另一种情况下接收到String,但是我应该可以从HashMap找到,忽略从流量中收到的情况。 / li>
  • During initialization program creates HashMap with user defined String
  • While processing an event (network traffic in my case) I might received String in a different case but I should be able to locate the from HashMap ignoring the case I received from traffic.

我遵循这种方法

CaseInsensitiveString.java

CaseInsensitiveString.java

    public final class CaseInsensitiveString {
            private String s;

            public CaseInsensitiveString(String s) {
                            if (s == null)
                            throw new NullPointerException();
                            this.s = s;
            }

            public boolean equals(Object o) {
                            return o instanceof CaseInsensitiveString &&
                            ((CaseInsensitiveString)o).s.equalsIgnoreCase(s);
            }

            private volatile int hashCode = 0;

            public int hashCode() {
                            if (hashCode == 0)
                            hashCode = s.toUpperCase().hashCode();

                            return hashCode;
            }

            public String toString() {
                            return s;
            }
    }

LookupCode.java

LookupCode.java

    node = nodeMap.get(new CaseInsensitiveString(stringFromEvent.toString()));

正因为如此,我为每个事件创建了一个新的CaseInsensitiveString对象。所以,它可能会击中性能。

Because of this, I'm creating a new object of CaseInsensitiveString for every event. So, it might hit performance.

有什么其他方法可以解决这个问题吗?

Is there any other way to solve this issue?

推荐答案

Map<String, String> nodeMap = 
    new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);

这真的是你需要的。

这篇关于不区分大小写的字符串作为HashMap键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 15:24