简体   繁体   English

如何正确使用hashSet? (从C ++移到Java)

[英]How to use hashSet properly? (moving from c++ to java)

I'm approaching (after c++) to java and, in particular, with android app development (Android studio) but I've some trouble with hashSet usage. 我正在(c ++之后)接触Java,尤其是在进行android应用开发(Android studio)时,但是在hashSet使用方面遇到了一些麻烦。 Here's is the issue: I cannot find a way to store map's keys obtained from "keySet()" method in any container; 这就是问题所在:我找不到在任何容器中存储从“ keySet()”方法获得的地图键的方法; I tried to store keys in a string vector or a list but an error occurs. 我试图将键存储在字符串向量或列表中,但发生错误。 How can I fix that? 我该如何解决?

This is a piece of code: 这是一段代码:

 private void fillMap(Map<String, String> map, String[] strings){

    String str;

    map.put("Question1", "answer1");
    map.put("Question2", "answer2");
    map.put("Question3", "answer3");

    Set<String> keys = map.keySet();


}

As you can see I created a map whose keys are questions and its values are answers. 如您所见,我创建了一个地图,其键是问题,其值是答案。 Then I created a Set where to put all the keys; 然后,我创建了一个Set,用于放置所有键; The problem is that I would try to store the content of the set in an ordered container but everything I tried gives me error. 问题是我将尝试将集合的内容存储在有序容器中,但是我尝试的所有操作都给了我错误。

Assume you have a Map<String, Integer> then its keySet() is a Set<String> an interface derived from the even more general Collection<String> . 假设您有Map<String, Integer>则其keySet()Set<String>这是从更通用的Collection<String>派生的接口。 This collection you can add to everything. 您可以将该集合添加到所有内容。

Set<String> keys = map.keySet();
List<String> list = new ArrayList<>(keys); // 1
list.sort();

Collections.addAll(list, keys); // or 2
Collections.sort(list); 

SortedSet<String> set = new TreeSet<>(keys);

And a warning to a C++ programmer: Vector is a very old inefficient class; 并警告C ++程序员:Vector是一个非常古老的低效类; use ArrayList instead, hence variables, parameters, result types List. 使用ArrayList代替,因此使用变量,参数,结果类型List。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM