验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

Java中Hashtable哈希表的遍历方式

阅读:727 来源:乙速云 作者:代码code

Java中Hashtable哈希表的遍历方式

在Java中,Hashtable是一个已经过时的集合类,建议使用HashMap替代。但是,如果你需要遍历Hashtable,可以使用以下几种方法:

  1. 使用keySet()和Iterator遍历:
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Hashtable hashtable = new Hashtable<>();
        hashtable.put("one", 1);
        hashtable.put("two", 2);
        hashtable.put("three", 3);

        Iterator> iterator = hashtable.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}
  1. 使用keySet()和for-each循环遍历:
import java.util.Hashtable;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Hashtable hashtable = new Hashtable<>();
        hashtable.put("one", 1);
        hashtable.put("two", 2);
        hashtable.put("three", 3);

        for (String key : hashtable.keySet()) {
            System.out.println("Key: " + key + ", Value: " + hashtable.get(key));
        }
    }
}
  1. 使用entrySet()和for-each循环遍历:
import java.util.Hashtable;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Hashtable hashtable = new Hashtable<>();
        hashtable.put("one", 1);
        hashtable.put("two", 2);
        hashtable.put("three", 3);

        for (Map.Entry entry : hashtable.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}
  1. 使用values()和for-each循环遍历:
import java.util.Hashtable;

public class Main {
    public static void main(String[] args) {
        Hashtable hashtable = new Hashtable<>();
        hashtable.put("one", 1);
        hashtable.put("two", 2);
        hashtable.put("three", 3);

        for (Integer value : hashtable.values()) {
            System.out.println("Value: " + value);
        }
    }
}

以上四种方法都可以实现Hashtable的遍历。但是,建议使用HashMap替代Hashtable,因为HashMap提供了更好的性能和更多的功能。

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>