小编Val*_*ous的帖子

ConcurrentHashMap 无法按预期工作

我正在计算电子选举的选票,并且在我的初始版本中我只有一个政党。每个选民将有不同的线程,线程将更新给定政党的选票计数。

我决定使用 ConcurrentHashMap,但结果不是我所期望的......

Map<String, Integer> voting = new ConcurrentHashMap<>();

for (int i = 0; i < 16; i++) {
  new Thread(() -> {
    voting.put("GERB", voting.getOrDefault("GERB", 0) + 1);
  }).start();
}

for (int i = 0; i < 100; i++) {
  voting.put("GERB", voting.getOrDefault("GERB", 0) + 1);
}

Thread.sleep(5000); // Waits for the threads to finish

for (String s : voting.keySet()) {
  System.out.println(s + ": " + voting.get(s));
}
Run Code Online (Sandbox Code Playgroud)

结果每次都不一样——范围从 114 到 116。

ConcurrentHashMap 不应该同步吗?

java concurrency hashmap concurrenthashmap java-8

11
推荐指数
1
解决办法
183
查看次数

将整数或十六进制值转换为 unicode 点

我正在尝试解决这个任务:http : //www.codeabbey.com/index/task_view/parity-control 但是作为输出,我在网站上得到了很多问号,在 Visual Studio 控制台中得到了很多空格。如果我尝试打印,比如 160 作为字符 (\'u0160') 一切正常,但是如果我将 int 转换为 char 我得到空白。我在互联网上搜索并尝试了一些从十六进制到 char 的转换,但它们的工作方式与将 int 转换为 char 的方式相同,我再次得到空格。

为什么我得到这些问号,我是否必须更改编码或其他什么?我可以从十六进制或 int 创建一个 unicode 点,然后只做:char output =convertedValue; 这是我执行上述任务的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Text.RegularExpressions;



class Program
{
    static void Main(string[] args)
    {

        string buffer = Console.ReadLine();
        string[] container = buffer.Split(' ');
        byte[] asciiCodes = new byte[container.Length];

        for (int i = 0; i < container.Length; i++)
        {
            asciiCodes[i] = byte.Parse(container[i]);
        } …
Run Code Online (Sandbox Code Playgroud)

c# unicode

5
推荐指数
1
解决办法
4939
查看次数

为什么 Go 中的 bool 类型是 16 个字节长?

我正在阅读“A Tour of Go”教程,并对其中一个示例进行了一些修改,发现 Go 中 bool 的大小是 16 个字节?!我是否没有使用正确的函数来计算这个值,或者 bool 的大小确实是 16 个字节?

package main

import "fmt"
import "unsafe"

func do(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("Twice %v is %v\n", v, v*2)
    case string:
        fmt.Printf("%q is %v bytes long\n", v, len(v))
    default:
        fmt.Printf("I don't know about type %T, but it's length is: %v bytes!\n", v, unsafe.Sizeof(v))
    }
}

func main() {
    do(21)
    do("hello")
    do(false)
}
Run Code Online (Sandbox Code Playgroud)

输出:

Twice 21 is 42
"hello" is 5 bytes long …
Run Code Online (Sandbox Code Playgroud)

size boolean go

0
推荐指数
1
解决办法
4767
查看次数

随机整数作为 hashCode

在构造函数中生成一个随机数并从hashCode方法返回这个值是个好主意吗?有可能发生冲突,但这适用于编写自己的hashCode方法。那么有什么缺点呢?在 HashMap 中使用此对象时,它将与随机数一起存储为散列,然后由相同的散列检索。如果有冲突,它们将被解决equals

java random hash hashcode

0
推荐指数
1
解决办法
497
查看次数

标签 统计

java ×2

boolean ×1

c# ×1

concurrency ×1

concurrenthashmap ×1

go ×1

hash ×1

hashcode ×1

hashmap ×1

java-8 ×1

random ×1

size ×1

unicode ×1