Java自学-集合框架 ArrayList和HashSet的区别
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java自学-集合框架 ArrayList和HashSet的区别,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2595字,纯文字阅读大概需要4分钟。
内容图文
![Java自学-集合框架 ArrayList和HashSet的区别](/upload/InfoBanner/zyjiaocheng/648/07543a7e4eeb4bfe99df0eb2c1984a6e.jpg)
Java ArrayList和HashSet的区别
示例 1 : 是否有顺序
ArrayList: 有顺序
HashSet: 无顺序
HashSet的具体顺序,既不是按照插入顺序,也不是按照hashcode的顺序。
以下是HasetSet源代码中的部分注释
/**
* It makes no guarantees as to the iteration order of the set;
* in particular, it does not guarantee that the order will remain constant over time.
*/
不保证Set的迭代顺序; 确切的说,在不同条件下,元素的顺序都有可能不一样
换句话说,同样是插入0-9到HashSet中, 在JVM的不同版本中,看到的顺序都是不一样的。 所以在开发的时候,不能依赖于某种臆测的顺序,这个顺序本身是不稳定的
package collection;
import java.util.ArrayList;
import java.util.HashSet;
public class TestCollection {
public static void main(String[] args) {
ArrayList<Integer> numberList =new ArrayList<Integer>();
//List中的数据按照插入顺序存放
System.out.println("----------List----------");
System.out.println("向List 中插入 9 5 1");
numberList.add(9);
numberList.add(5);
numberList.add(1);
System.out.println("List 按照顺序存放数据:");
System.out.println(numberList);
System.out.println("----------Set----------");
HashSet<Integer> numberSet =new HashSet<Integer>();
System.out.println("向Set 中插入9 5 1");
//Set中的数据不是按照插入顺序存放
numberSet.add(9);
numberSet.add(5);
numberSet.add(1);
System.out.println("Set 不是按照顺序存放数据:");
System.out.println(numberSet);
}
}
示例 2 : 能否重复
List中的数据可以重复
Set中的数据不能够重复
重复判断标准是:
首先看hashcode是否相同
如果hashcode不同,则认为是不同数据
如果hashcode相同,再比较equals,如果equals相同,则是相同数据,否则是不同数据
package collection;
import java.util.ArrayList;
import java.util.HashSet;
public class TestCollection {
public static void main(String[] args) {
ArrayList<Integer> numberList =new ArrayList<Integer>();
//List中的数据可以重复
System.out.println("----------List----------");
System.out.println("向List 中插入 9 9");
numberList.add(9);
numberList.add(9);
System.out.println("List 中出现两个9:");
System.out.println(numberList);
System.out.println("----------Set----------");
HashSet<Integer> numberSet =new HashSet<Integer>();
System.out.println("向Set 中插入9 9");
//Set中的数据不能重复
numberSet.add(9);
numberSet.add(9);
System.out.println("Set 中只会保留一个9:");
System.out.println(numberSet);
}
}
练习: 不重复的随机数
生成50个 0-9999之间的随机数,要求不能有重复的
答案 :
package collection;
import java.util.HashSet;
import java.util.Set;
public class TestCollection {
public static void main(String[] args) {
Set<Integer> numbers =new HashSet<>();
while(numbers.size()<50){
int i = (int) (Math.random()*10000);
numbers.add(i);
}
System.out.println("得到50个不重复随机数:");
System.out.println(numbers);
}
}
内容总结
以上是互联网集市为您收集整理的Java自学-集合框架 ArrayList和HashSet的区别全部内容,希望文章能够帮你解决Java自学-集合框架 ArrayList和HashSet的区别所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。