English 中文(简体)
高效地比较比特集合
原标题:Compare bit sets efficiently

我想在Java中使用位集存储权限以便高效地比较它们。 1表示授权,0表示拒绝权限。 如果授权已完成,则需要的权限将与权限集进行比较。

我的想法是使用AND运算符并将结果与所请求的权限进行比较。

例子:

     0010 1101 Granted Permissions
AND  0000 0101 Requested Permissions
=    0000 0101 Result

if (Result == Requested Permissions)
    allow
else
    deny

能否更高效或更简单地完成?

最佳回答

我将专注于“简单”部分,因为我认为这个操作不会成为任何严重的应用程序性能瓶颈。

你可以使用具有所有必要操作的 BitSet

更面向对象的方法、更易于理解和阅读的方法是使用enum表示您的权限,并使用EnumSet。对于只有少量值的枚举,它的性能将与BitSet几乎相同,因为它将使用非常类似的实现。

问题回答

如果您使用的是 Java 5 或更高版本,我建议使用EnumEnumSet。它更容易处理,据我所知,性能也同样出色。

你的方法非常好,预期会起作用。当然,你可以用更多复杂的方法来达到同样的效果,但我认为在上下文环境相符的情况下使用位操作符没有任何问题。毕竟,这些操作符是 Java 核心语言的一部分,而且没有被标记为@deprecated@evil





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签